0% found this document useful (0 votes)
25 views12 pages

Set in Kotlin

The document discusses various functions and operations that can be performed on Kotlin Sets. It explains how to create and initialize immutable and mutable sets, perform operations like contains, union, map, reduce, fold, chunked, and partition on sets.

Uploaded by

a7813010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views12 pages

Set in Kotlin

The document discusses various functions and operations that can be performed on Kotlin Sets. It explains how to create and initialize immutable and mutable sets, perform operations like contains, union, map, reduce, fold, chunked, and partition on sets.

Uploaded by

a7813010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Set in Kotlin

Kotlin Set interface is a generic unordered collection of elements and it does not contain
duplicate elements. Kotlin supports two types of sets mutable and immutable.
setOf() is immutable means it supports only read-only functionalities and
mutableSetOf() is mutable means it supports read and write both functionality.

Sets are:
 An unordered collection of elements.
 Duplicate elements are not allowed in sets.

fun main()
{
//declaring a set of strings
val seta = setOf("Hello" , "to", "All")
//declaring a set of characters
val setb = setOf( "A" , "B" , "C" )
//declaring a set of integers
val setc = setOf( 1 ,2 , 3 , 4 )

//traversing through a set of strings


for(item in seta)
print( item )
println()
//traversing through a set of characters
for(item in setb)
print( item )
println()
//traversing through a set of integers
for(item in setc)
print( "$item ")
}

Output:
HellotoAll
ABC
1234

fun main() {

val words2 = setOf("pen", "cup", "ball", "pen", "spectacles")


words2.forEach { e -> println(e)}
}
Output:
pen
cup
ball
spectacles

Functions:
 elementAt(index): Returns the element at the specified index in the set or
throws IndexOutOfBoundsException.
 contains(element): Returns true if element exists in the set or returns false.
 indexOf(element): Returns the index of the specified element in the set, or -1
if the specified element is not present in the set.
 lastIndexOf(element): Returns the index of the last occurrence (or the only
occurrence) of the specified element in the set, or -1 if the specified element
is not present in the set.
 first(): Returns first element in set or throws NoSuchElementException if set is
empty.
 last(): Returns last element in set or throws NoSuchElementException if set is
empty.
 isEmpty(): Returns true if set is empty else false.
 count(): Returns the number of elements in this collection.
 sum(): Returns the sum of all elements in this collection.
 average(): Returns the average of all elements in this collection.

fun main() {
val languages = setOf<String>("Kotlin", "C++", "C", "Java", "Angular", "Kotlin")
val marks = setOf<Int>(95,96,94,90)
println("The size of set is: ${languages.size}")
println("Does Java exist in set: ${languages.contains("Java")}")
println("Does PHP exist in set: ${languages.contains("PHP")}")
println("Element at index 1: ${languages.elementAt(1)}")
println("The index of Kotlin is: ${languages.indexOf("Kotlin")}")
println("The index of PHP is: ${languages.indexOf("PHP")}")
println("The last index of Kotlin is: ${languages.lastIndexOf("Kotlin")}")
println("First element in set: ${languages.first()}")
println("Last element in set: ${languages.last()}")
println("Is set empty: ${languages.isEmpty()}")
// Mathematical functions
println("No. of elements in set: ${marks.count()}")
println("Sum of elements in set: ${marks.sum()}")
println("Average of elements in set: ${marks.average()}")
}
Output:

The size of set is: 5


Does Java exist in set: true
Does PHP exist in set: false
Element at index 1: C++
The index of Kotlin is: 0
The index of PHP is: -1
The last index of Kotlin is: 0
First element in set: Kotlin
Last element in set: Angular
Is set empty: false
No. of elements in set: 4
Sum of elements in set: 375
Average of elements in set: 93.75

contains() and containsAll() functions –

Both the methods are used to check whether an element is present in the set or
not?

Kotlin program of using contains() and containsAll() function –


fun main(args: Array<String>){
val captains = setOf(1,2,3,4,"Kohli","Smith", "Root","Malinga","Rohit","Dhawan")

var name = "Dhawan"


println("The set contains the element $name or not?" + " "+captains.contains(name))

var num = 5
println("The set contains the element $num or not?" +" "+captains.contains(num))

println("The set contains the given elements or not?" + " "+


captains.containsAll(setOf(1,3,"Root")))
}

Output:

The set contains the element Dhawan or not? true


The set contains the element 5 or not? false
The set contains the given elements or not? true
Checking equality of empty sets and use of isEmpty() functions –
fun main(args: Array<String>) {
//creating an empty set of strings
val seta = setOf<String>()
//creating an empty set of integers
val setb =setOf<Int>()

//checking if set is empty or not


println("seta.isEmpty() is ${seta.isEmpty()}")
// Since Empty sets are equal
//checking if two sets are equal or not
println("seta == setb is ${seta == setb}")
println(seta) //printing first set
}

Output :

seta.isEmpty() is true
seta == setb is true
[]

Kotlin mutable Set


With mutableSetOf, we can create mutable sets in Kotlin.

fun main() {
val nums = mutableSetOf(3, 4, 5)
println(nums)
nums.add(6)
nums.add(7)
nums.addAll(setOf(8, 9, 10))

println(nums)
nums.remove(10)
println(nums)
nums.clear()
if (nums.isEmpty()) println("The set is empty")
else println("The set is not epty")
}
Output :
[3, 4, 5]
[3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9]
The set is empty
The example creates a mutable set and presents several its methods.

val nums = mutableSetOf(3, 4, 5)

We create a mutable set of three integer elements.

nums.add(6)
nums.add(7)
nums.addAll(setOf(8, 9, 10))

The add adds a new element at the end of the set. The addAll adds multiple
elements at the end of the set.

nums.clear()

The clear method removes all elements from the set.

if (nums.isEmpty()) println("The set is empty")


else println("The set is not epty")

With the isEmpty method we check if the set is empty.

[3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9]
[]
The set is empty

Kotlin Set union

The union operation returns a set containing all distinct elements from both
collections.

fun main() {

val nums = setOf(1, 2, 3)


val nums2 = setOf(3, 4, 5)

val nums3 = nums.union(nums2)

println(nums3)
}
In the example, we have two sets of integers. We join the sets with the union
method.

[1, 2, 3, 4, 5]

Kotlin Set map

The mapping operation returns a modified list by applying a transform function on


each element of the set.

fun main() {

val nums = setOf(1, 2, 3, 4, 5, 6)


val nums2 = nums.map { e -> e * 2 }
println(nums2)
}

We have a set of integers. With the map function, we multiply each set element by
2. The function returns a new list.

[2, 4, 6, 8, 10, 12]

Kotlin Set reduction

Reduction is a terminal operation that aggregates set values into a single value.
The reduce method applies a function against an accumulator and each element
(from left to right) to reduce it to a single value.

fun main() {

val nums = setOf(4, 5, 3, 2, 1, 7, 6, 8, 9)

val sum = nums.reduce { total, next -> total + next }


println(sum)
}

In the example, we use the reduce operation on a set of integers.

val sum = nums.reduce { total, next -> total + next }

We calculate the sum of values. The total is the accumulator, the next is the next
value in the list.

45
Kotlin Set fold

The folding operation is similar to the reduction. Folding is a terminal operation


that aggregates set values into a single value. The difference is that folding starts
with an initial value.

fun main() {

val expenses = setOf(20, 40, 80, 15, 25)

val cash = 550

val res = expenses.fold(cash) {total, next -> total - next}


println(res)
}

We have a set of expenses. These expenses are applied on the initial amount of
cash available.

val res = expenses.fold(cash) {total, next -> total - next}

With the fold we deduce all the expenses from the cash and return the remaining
value.

370

This is the amount that we have after subtracting all the expenses on the available
amount of money.

Kotlin Set chunked

Sometimes we need to work with more elements of a set when doing reductions.
We can use the chunked method to split the set into a list of lists.

fun main() {

val nums = setOf(1, 2, 3, 4, 5, 6)

val res = nums.chunked(2).fold(0) { total, next -> total + next[0] * next[1] }

println(res)
}

In the example, we have a set of six values. We want to achieve the following
operation: 1*2 + 3*4 + 5*6. For this, we need to split the list into chunks of two
values.

val res = nums.chunked(2).fold(0) { total, next -> total + next[0] * next[1] }

We split the set into a list of two-element lists and apply a fold on it. The next is a
list on which we can use the indexing operations.

44

Kotlin Set partition

The partition operation splits the original collection into pair of lists. The first list
contains elements for which the specified predicate yields true, while the second
list contains elements for which the predicate yields false.

fun main() {

val nums = setOf(4, -5, 3, 2, -1, 7, -6, 8, 9)

val (nums2, nums3) = nums.partition { e -> e < 0 }

println(nums2)
println(nums3)
}

We have a set of integers. With the partition method, we split the set into two
sublists; one contains negative, the other one positive values.

val (nums2, nums3) = nums.partition { e -> e < 0 }

Using destructuring declaration, we split the set into two parts in one go.

[-5, -1, -6]


[4, 3, 2, 7, 8, 9]
Kotlin Set groupBy

The groupBy method groups elements of the original set by the key returned by the
given selector function, applied to each element. It returns a map where each
group key is associated with a list of corresponding elements.

fun main() {

val nums = setOf(1, 2, 3, 4, 5, 6, 7, 8)

val res = nums.groupBy { if (it % 2 == 0) "even" else "odd" }


println(res)

val words = setOf("as", "pen", "cup", "doll", "my", "dog", "spectacles")

val res2 = words.groupBy { it.length }


println(res2)
}

The example shows how to use the groupBy method.

val nums = setOf(1, 2, 3, 4, 5, 6, 7, 8)

val res = nums.groupBy { if (it % 2 == 0) "even" else "odd" }


println(res)

These lines create a map, which has two keys: "even" and "odd". The "even"
points to a list of even values and the "odd" to a list of odd values.

val words = setOf("as", "pen", "cup", "doll", "my", "dog", "spectacles")

val res2 = words.groupBy { it.length }

Here we create a map with integer keys. Each key groups words that have a
certain length.

{odd=[1, 3, 5, 7], even=[2, 4, 6, 8]}


{2=[as, my], 3=[pen, cup, dog], 4=[doll], 10=[spectacles]}

Kotlin Set any

The any method returns true if at least one element matches the given predicate
function.
fun main() {

val nums = setOf(4, 5, 3, 2, -1, 7, 6, 8, 9)

val r = nums.any { e -> e > 10 }


if (r) println("There is a value greater than ten")
else println("There is no value greater than ten")

val r2 = nums.any { e -> e < 0 }


if (r2) println("There is a negative value")
else println("There is no negative value")

The example shows the usage of any.

val r2 = nums.any { e -> e < 0 }

Here we check if the set contains at least one negative value. The method returns
a Boolean value.

Kotlin Set all

The all returns true if all elements satisfy the given predicate function.

fun main() {

val nums = setOf(4, 5, 3, 2, -1, 7, 6, 8, 9)


val nums2 = setOf(-3, -4, -2, -5, -7, -8)

// testing for positive only values


val r = nums.all { e -> e > 0 }

if (r) println("nums set contains only positive values")


else println("nums set does not contain only positive values")

// testing for negative only values


val r2 = nums2.all { e -> e < 0 }

if (r2) println("nums2 set contains only negative values")


else println("nums2 set does not contain only negative values")
}

The example shows the usage of all.

// testing for positive only values


val r = nums.all { e -> e > 0 }
Here we test if the nums set contains only positive values.

Kotlin Set drop

With the drop operations, we exclude some elements from the set.

fun main() {

val nums = setOf(4, 5, 3, 2, 1, -1, 7, 6, -8, 9, -12)

val nums2 = nums.drop(3)


println(nums2)

val nums3 = nums.sorted().dropWhile { e -> e < 0 }


println(nums3)

val nums4 = nums.sorted().dropLastWhile { e -> e > 0 }


println(nums4)
}

The example shows the usage of different drop operations.

val nums2 = nums.drop(3)

With the drop method, we exclude the first three elements.

val nums3 = nums.sorted().dropWhile { e -> e < 0 }

With the dropWhile method, we exclude the first n elements that satisfy the given
predicate function.

val nums4 = nums.sorted().dropLastWhile { e -> e > 0 }

With the dropLastWhile method, we exclude the last n elements that satisfy the
given predicate function.

[2, 1, -1, 7, 6, -8, 9, -12]


[1, 2, 3, 4, 5, 6, 7, 9]
[-12, -8, -1]

Kotlin List take

The take operations are complementary to the drop operations. The take methods
form a new list by picking some of the set elements.
fun main() {

val nums = setOf(4, 5, 3, 2, 1, -1, 7, 6, -8, 9, -12)

val nums2 = nums.take(3)


println(nums2)

val nums3 = nums.sorted().take(3)


println(nums3)

val nums4 = nums.takeWhile { e -> e > 0 }


println(nums4)

val nums5 = nums.sortedDescending().takeWhile { e -> e > 0 }


println(nums5)
val nums6 = nums.takeIf { e -> e.contains(6) }
println(nums6)
}

The example shows the usage of various take methods.

val nums2 = nums.take(3)

The take method creates a new list having the first three elements of the original
set.

val nums4 = nums.takeWhile { e -> e > 0 }

The takeWhile takes the first n elements that satisfy the predicate function.

val nums6 = nums.takeIf { e -> e.contains(6) }

The takeIf methods takes all elements of the set if the condition in the predicate
function is met.

[4, 5, 3]
[-12, -8, -1]
[4, 5, 3, 2, 1]
[9, 7, 6, 5, 4, 3, 2, 1]
[4, 5, 3, 2, 1, -1, 7, 6, -8, 9, -12]

You might also like