Kotlin Set Tutorial with Examples

In the previous tutorial, we have covered the Kotlin List Tutorial with Examples. In this tutorial, we will learn the usage of important Kotlin Set interface methods with an example. 

A Kotlin Set is a generic unordered collection of elements which allows no duplicates.

Key points of Set:
  • Methods in this interface supports only read-only access to the set; read/write access is supported through the MutableSet interface.
  • Kotlin distinguishes between read-only and mutable sets. Read-only sets are created with setOf() and mutable set with mutableSetOf().
  • MutableSet is a Set with write operations from MutableCollection.
  • The default implementation of Set – LinkedHashSet – preserves the order of elements insertion. Hence, the functions that rely on the order, such as first() or last(), return predictable results on such sets.

Let's demonstrates the usage of important Kotlin Set interface methods with an example.

Kotlin setOf()

The setOf() method creates a new read-only set in Kotlin. A set cannot contain duplicate elements.

The example creates a new set with setOf(). The size of the set is determined with the size attribute.
package net.sourcecodeexamples.kotlin

fun main() {
    // Set contains unique elements
    val theSet = setOf("one", "two", "three", "one")
    println(theSet)
    println("The set contains ${theSet.size} elements.")
}
Output:
[one, two, three]
The set contains 3 elements.

Kotlin mutableSetOf()

With mutableSetOf(), we can create mutable sets in Kotlin.

The following example creates a mutable set and presents several of its methods.
package net.sourcecodeexamples.kotlin

fun main(args: Array < String > ) {

    val nums = mutableSetOf(3, 4, 5)

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

    println(nums)

    nums.remove(10)

    println(nums)

    nums.retainAll(setOf(12, 14, 16, 18))

    println(nums)

    nums.clear()

    if (nums.isEmpty()) println("The set is empty")
    else println("The set is not epty")
}
Output:
[3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9]
[]
The set is empty

Kotlin Set indexing

Each element of a set has an index. Kotlin set indexes to start from zero. The last element has len-1 index.

The following example presents the Kotlin Set indexing operations.
package net.sourcecodeexamples.kotlin

fun main() {

    val fruits = setOf("banana", "mango", "apple", "orange", "banana")

    val w1 = fruits.elementAt(0);
    println(w1)

    val i1 = fruits.indexOf("banana")
    println("The first index of banana is $i1")

    val i2 = fruits.lastIndexOf("banana")
    println("The last index of banana is $i2")
}
Output:
banana
The first index of banana is 0
The last index of banana is 0

Kotlin Set count

The count() method returns the number of elements in the set.

The example returns the number of values in the set, the number of negative values and the number of even values.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = setOf(12, 1,2,5,4,2)

    val len = nums.count()
    println("There are $len elements")
    
    val size = nums.size
    println("The size of the list is $size")    

    val n1 = nums.count { e -> e < 0 }
    println("There are $n1 negative values")

    val n2 = nums.count { e -> e % 2 == 0 }
    println("There are $n2 even values")
}
Output:
There are 5 elements
The size of the list is 5
There are 0 negative values
There are 3 even values

Kotlin Set first and last elements

Let's see how to get first and the last elements of the Set in Kotlin.

The example creates a list of fruits. We get the first and the last elements of the list.
package net.sourcecodeexamples.kotlin

fun main() {

    val fruits = setOf("banana", "mango", "apple", "orange")

    val w1 = fruits.first()
    println(w1)

    val w2 = fruits.last()
    println(w2)

    val w3 = fruits.findLast { w -> w.startsWith('a') }
    println(w3)

    val w4 = fruits.first { w -> w.startsWith('o') }
    println(w4)
}
Output:
banana
orange
apple
orange

Kotlin Set iterate

Five ways to iterate over a Set in Kotlin.

  1. Using forEach() method
  2. Using for loop
  3. An alternative for cycle utilizes the size of the list
  4. Using forEachIndexed() method
  5. Using a Iterator and a while loop
Here is a complete source code to demonstrate five ways of looping over a Set in Kotlin:

package net.sourcecodeexamples.kotlin


fun main() {

    val fruits = setOf("banana", "mango", "apple", "orange", "banana")

    // using forEach() method
    fruits.forEach {
        e - > print("$e ")
    }
    println()

    // using for loop
    for (fruit in fruits) {

        print("$fruit ")
    }

    println()

    // An alternative for cycle utilizes the size of the list
    for (i in 0 until fruits.size) {

        print("${fruits.elementAt(i)} ")
    }

    println()
    // using forEachIndexed() method
    fruits.forEachIndexed({
        i,
        e - > println("fruits[$i] = $e")
    })


    val it: Iterator < String > = fruits.asIterable().iterator();

    while (it.hasNext()) {

        val e = it.next()
        print("$e ")
    }
    println()
}
Output:
banana mango apple orange 
banana mango apple orange 
banana mango apple orange 
fruits[0] = banana
fruits[1] = mango
fruits[2] = apple
fruits[3] = orange
banana mango apple orange 

Kotlin Set Sort Example - Ascending and Descending Order

Since the sets created with setOf() are read-only, the methods do not alter the set but return a new modified list.

The example sorts set of values in ascending and descending order and reverse list elements.
package net.sourcecodeexamples.kotlin

fun main() {

 val nums = setOf(10, 5, 3, 4, 2, 1, 11, 14, 12)

 val sortAsc = nums.sorted()
 println("sortAsc -> " + sortAsc)

 val sortDesc = nums.sortedDescending()
 println("sortDesc -> " + sortDesc)

 val revNums = nums.reversed()
 println("revNums -> " + revNums)
}
Output:
sortAsc -> [1, 2, 3, 4, 5, 10, 11, 12, 14]
sortDesc -> [14, 12, 11, 10, 5, 4, 3, 2, 1]
revNums -> [12, 14, 11, 1, 2, 4, 3, 5, 10]

Kotlin Set contains

This example shows how to use contains() method to check if a set contains the specified elements.
package net.sourcecodeexamples.kotlin

fun main() {

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

 val r = nums.contains(4)

 if (r) {
  println("The list contains 4")
 } else {
  println("The list does not contain 4")
 }
 val r2 = nums.containsAll(listOf(1, 6))

 if (r2) {
  println("The list contains 1 and 6")
 } else {
  println("The list does not contain 1 and 6")
 }
}
Output:
The list contains 4
The list contains 1 and 6

Kotlin Set union 

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

In the example, we have two sets of integers. We join the sets with the union() method.
package net.sourcecodeexamples.kotlin

fun main(args: Array<String>) {

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

    val nums3 = nums.union(nums2)

    println(nums3)
}
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Kotlin Set filter 

Filtering is an operation where only elements that meet certain criteria pass through.

The following example presents the filtering operation on Kotlin sets.
package net.sourcecodeexamples.kotlin

fun main(args: Array<String>) {

    val fruits = setOf("banana", "mango", "apple", "orange")

    val fruits1 = fruits.filter { e -> e.length == 5 }
    fruits1.forEach { e -> print("$e ") }

    println()

    val fruits2 = fruits.filterNot { e -> e.length == 5 }

    fruits2.forEach { e -> print("$e ") }
    println()
}
Output:
mango apple 
banana orange 

Kotlin Set any

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

The following example shows the usage of any() method in Set in Kotlin.
package net.sourcecodeexamples.kotlin

fun main() {

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

    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")
    }
}

Output:
There is no value greater than ten
There is a negative value

Kotlin Set all

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

The following example shows the usage of all() method in Kotlin.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = setOf(1,2,3,4,5,6,7,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 list contains only positive values")
    } else {
       println("nums list does not contain only positive values")
    }


    // testing for negative only values
    val r2 = nums2.all { e -> e < 0 }

    if (r2) {
        println("nums2 list contains only negative values")
    } else {
        println("nums2 list does not contain only negative values")
    }
}
Output:
nums list contains only positive values
nums2 list contains only negative values

Conclusion

That’s all folks. In this tutorial, we have covered Kotlin sets with examples. The source code of this tutorial available on my GitHub repository at https://github.com/RameshMF/kotlin-tutorial.

Thank you for reading. See you in the next post.

References

The source code of this tutorial available on my GitHub Repository.

Comments