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.
For set creation, use the standard library functions setOf() for read-only sets and mutableSetOf() for mutable sets.
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]

There are various ways to loop through a Kotlin Set. Lets study them one by one:
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]

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

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

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

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 can be used to check the existence of an element in a set.
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 can also be used to check the existence of an element in a set.
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 returns true if the collection is empty (contains no elements), false otherwise.
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 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.
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 can be used to get the element at the specified index in the set.
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

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.
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]

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.
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]

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]

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]

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]

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]

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]}

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]

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]]

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]]

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]

Q 1 - Can we make a mutable Kotlin set as immutable?
A - Yes
B - No
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
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
elementAt() method is used to get the list element from the given index.

    68 Lectures 
     4.5 hours 

 Arnab Chakraborty

    71 Lectures 
     5.5 hours 

 Frahaan Hussain

    18 Lectures 
     1.5 hours 

 Mahmoud Ramadan

    49 Lectures 
     6 hours 

 Catalin Stefan

    49 Lectures 
     2.5 hours 

 Skillbakerystudios

    22 Lectures 
     1 hours 

 CLEMENT OCHIENG
 Print
 Add Notes
 Bookmark this page