Kotlin - Sets


Kotlin set is an unordered collection of items. A Kotlin set can be either mutable (mutableSetOf) or read-only (setOf). Kotlin mutable or immutable sets do not allow to have duplicate elements.

Creating Kotlin Sets

For set creation, use the standard library functions setOf() for read-only sets and mutableSetOf() for mutable sets.

A read-only view of a mutable set can be obtained by casting it to Set.

Example

fun main() {
    val theSet = setOf("one", "two", "three", "four")
    println(theSet)
    
    val theMutableSet = mutableSetOf("one", "two", "three", "four")
    println(theMutableSet)
}

When you run the above Kotlin program, it will generate the following output:

[one, two, three, four]
[one, two, three, four]

Loop through Kotlin Sets

There are various ways to loop through a Kotlin Set. Lets study them one by one:

Using toString() function

fun main() {
    val theSet = setOf("one", "two", "three", "four")
    println(theSet.toString())
}

When you run the above Kotlin program, it will generate the following output:

[one, two, three, four]

Using Iterator

fun main() {
    val theSet = setOf("one", "two", "three", "four")
    
   val itr = theSet.asIterable().iterator()
    while (itr.hasNext()) {
        println(itr.next())
    }
}

When you run the above Kotlin program, it will generate the following output:

one
two
three
four

Using for loop

fun main() {
   val theSet = setOf("one", "two", "three", "four")
    
   for (i in theSet.indices) {
      println(theSet.elementAt(i))
   }
}

When you run the above Kotlin program, it will generate the following output:

one
two
three
four

Using forEach

fun main() {
   val theSet = setOf("one", "two", "three", "four")
    
   theSet.forEach { println(it) }
}

When you run the above Kotlin program, it will generate the following output:

one
two
three
four
Note - here it works like this operator in Java.

Size of Kotlin Set

We can use size property to get the total number of elements in a set:

fun main() {
    val theSet = setOf("one", "two", null, "four", "five")
    
    println("Size of the Set " + theSet.size)
}

When you run the above Kotlin program, it will generate the following output:

Size of the Set 5

The "in" Operator

The in operator can be used to check the existence of an element in a set.

Example

fun main() {
   val theSet = setOf("one", "two", "three", "four")
    
   if("two" in theSet){
      println(true)
   }else{
      println(false)
   }
}

When you run the above Kotlin program, it will generate the following output:

true

The contain() Method

The contain() method can also be used to check the existence of an element in a set.

Example

fun main() {
   val theSet = setOf("one", "two", "three", "four")

   if(theSet.contains("two")){
      println(true)
   }else{
      println(false)
   }
    
}

When you run the above Kotlin program, it will generate the following output:

true

The isEmpty() Method

The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise.

Example

fun main() {
   val theSet = setOf("one", "two", "three", "four")
    
   if(theSet.isEmpty()){
      println(true)
   }else{
      println(false)
   }
}

When you run the above Kotlin program, it will generate the following output:

false

The indexOf() Method

The indexOf() method returns the index of the first occurrence of the specified element in the set, or -1 if the specified element is not contained in the set.

Example

fun main() {
   val theSet = setOf("one", "two", "three", "four")
    
   println("Index of 'two' -  " + theSet.indexOf("two"))
}

When you run the above Kotlin program, it will generate the following output:

Index of 'two' -  1

The elementAt() Method

The elementAt() method can be used to get the element at the specified index in the set.

Example

fun main() {
   val theSet = setOf("one", "two", "three", "four")

   println("Element at 3rd position " + theSet.elementAt(2))
}

When you run the above Kotlin program, it will generate the following output:

Element at 3rd position three

Set Addition

We can use + operator to add two or more sets into a single set. This will add second set into first set, discarding the duplicate elements.

Example

fun main() {
    val firstSet = setOf("one", "two", "three")
    val secondSet = setOf("one", "four", "five", "six")
    val resultSet = firstSet + secondSet
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[one, two, three, four, five, six]

Set Subtraction

We can use - operator to subtract a set from another set. This operation will remove the common elements from the first set and will return the result.

Example

fun main() {
    val firstSet = setOf("one", "two", "three")
    val secondSet = setOf("one", "five", "six")
    val resultSet = firstSet - secondSet
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[two, three]

Removing null a Set

We can use filterNotNull() method to remove null element from a set.

fun main() {
    val theSet = setOf("one", "two", null, "four", "five")
    val resultSet = theSet.filterNotNull()
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[one, two, four, five]

Sorting Elements

We can use sorted() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order.

fun main() {
    val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0)
    var resultSet = theSet.sorted()
    println(resultSet)
    
    resultSet = theSet.sortedDescending()
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[-1, 0, 10, 20, 30, 31, 40, 50]
[50, 40, 31, 30, 20, 10, 0, -1]

Filtering Elements

We can use filter() method to filter out the elements matching with the given predicate.

fun main() {
    val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0)
    val resultSet = theSet.filter{ it > 30}
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[31, 40, 50]

Dropping First N Elements

We can use drop() method to drop first N elements from the set.

fun main() {
    val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0)
    val resultSet = theSet.drop(3)
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[31, 40, 50, -1, 0]

Grouping Set Elements

We can use groupBy() method to group the elements matching with the given predicate.

fun main() {
    val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)
    val resultSet = theSet.groupBy{ it % 3}
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

{1=[10, 31, 40], 0=[12, 30, 9, -3, 0]}

Mapping Set Elements

We can use map() method to map all elements using the provided function:.

fun main() {
    val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)
    val resultSet = theSet.map{ it / 3 }
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[3, 4, 10, 10, 13, 3, -1, 0]

Chunking Set Elements

We can use chunked() method to create chunks of the given size from a set. Last chunk may not have the elements equal to the number of chunk size based on the total number of elements in the set.

fun main() {
    val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)
    val resultSet = theSet.chunked(3)
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[[10, 12, 30], [31, 40, 9], [-3, 0]]

Windowing Set Elements

We can use windowed() method to a set of element ranges by moving a sliding window of a given size over a collection of elements.

fun main() {
    val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)
    val resultSet = theSet.windowed(3)
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[[10, 12, 30], [12, 30, 31], [30, 31, 40], [31, 40, 9], [40, 9, -3], [9, -3, 0]]

By default, the sliding window moves one step further each time but we can change that by passing a custom step value:

fun main() {
    val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)
    val resultSet = theSet.windowed(3, 3)
    
    println(resultSet)
}

When you run the above Kotlin program, it will generate the following output:

[[10, 12, 30], [31, 40, 9]]

Kotlin mutable Set

We can create mutable set using mutableSetOf(), later we can use add() to add more elements in the same set, and we can use remove() method to remove the elements from the set.

fun main() {
    val theSet = mutableSetOf(10, 20, 30)
    
    theSet.add(40)
    theSet.add(50)
    println(theSet)
    
    theSet.remove(10)
    theSet.remove(30)
    println(theSet)
    
}

When you run the above Kotlin program, it will generate the following output:

[10, 20, 30, 40, 50]
[20, 40, 50]

Quiz Time (Interview & Exams Preparation)

Q 1 - Can we make a mutable Kotlin set as immutable?

A - Yes

B - No

Answer : A

Explanation

Yes we can make a mutable set to immutable by casting them to Set

Q 2 - We can add two or more sets and create a single set using + operator:

A - True

B - False

Answer : A

Explanation

Yes we can add or subtract two Kotlin sets and generate a third set. A plus sign works like a union() for set.

Q 2 - Which method will return an item from the given index of Kotlin set?

A - get()

B - elementAt()

C - Direct index with set variable

D - None of the above

Answer : B

Explanation

elementAt() method is used to get the list element from the given index.

Advertisements