In this tutorial, we will talk about Kotlin Set with the help of simple examples. Sets are:
- An unordered collection of elements.
- Duplicate elements are not allowed in sets.
In Kotlin, we can have both a mutable set and an immutable set.
Kotlin Immutable Set
The immutable set also known as read-only set support only read-only access to the set.
Immutable set are created using setOf() and setOf<T>() functions.
Create and initialize Set
The below example show you how to:
- initialize Set using setOf() (contains elements of all type), setOf<T>() (contains elements of specific type) functions.
- create new Set from another Set with the same elements using toSet() function.
val set1 = setOf("Arun", 10, 1.05f, 'a', null, 10)
val set2 = setOf<String>("Arun", "Neha", "Monika")
val set3 = set2.toSet()
println(set1) //[Arun, 10, 1.05, a, null]
println(set2) //[Arun, Neha, Monika]
println(set3) //[Arun, Neha, Monika]
Access items from Set
The below example show you how to:
- find the size of a Set using size property or count() method.
- get the IntRange for Set using Indices.
- check if a Set is empty or not using isEmpty() or isNotEmpty().
- access the element at specified index in a Set using elementAt(Index), elementAtOrElse(Index , defaultValue), elementAtOrNull(Index).
val languageSet = setOf<String>("Kotlin", "C++", "C", "Java", "Angular", "Kotlin")
println("The size of set is: ${languageSet.size}")
//The size of set is: 5
println("IntRange for set: ${languageSet.indices}")
//IntRange for set: 0..4
println("The size of set using count(): ${languageSet.count()}")
//The size of set using count(): 5
println("Is set empty: ${languageSet.isEmpty()}")
//Is set empty: false
println("Is set not empty: ${languageSet.isNotEmpty()}")
//Is set not empty: true
println("Element at index 1: ${languageSet.elementAt(1)}")
//Element at index 1: C++
println("Element at index 5 or '-1' if index is out of bounds: ${languageSet.elementAtOrElse(5, { -1 })}")
//Element at index 5 or '-1' if index is out of bounds: -1
println("Element at index 6 or 'null' if index is out of bounds: ${languageSet.elementAtOrNull(6)}")
//Element at index 6 or 'null' if index is out of bounds: null
Find elements in Set
The below example show how to:
- check if a Set contains an element or not using contains()
- check if a Set contains all given elements or not using containsAll()
- find the index of the first/last occurrence of an element using indexOf() / lastIndexOf()
- find the first/last element of the Set using first()/last()
- find the index of the first/last occurrence of an element that matches a condition using indexOfFirst() / indexOfLast()
- find the first/last element in the Set that matches a condition using find() / findLast()
val languageSet = setOf<String>("Kotlin", "C", "C++", "Java", "Angular", "Kotlin")
println("Does Java exist in set: ${languageSet.contains("Java")}")
//Does Java exist in set: true
println("Does PHP exist in set: ${languageSet.contains("PHP")}")
//Does PHP exist in set: false
println("Does specified set exist in languageSet: ${languageSet.containsAll(setOf("C", "Java"))}")
//Does specified set exist in languageSet: true
println("The index of Kotlin is: ${languageSet.indexOf("Kotlin")}")
//The index of Kotlin is: 0
println("The index of PHP is: ${languageSet.indexOf("PHP")}")
//The index of PHP is: -1
println("The last index of Kotlin is: ${languageSet.lastIndexOf("Kotlin")}")
//The last index of Kotlin is: 0
println("First element in set: ${languageSet.first()}")
//First element in set: Kotlin
println("Last element in set: ${languageSet.last()}")
//Last element in set: Angular
println(languageSet.indexOfFirst { e -> e.startsWith('C') })//1
println(languageSet.indexOfFirst { e -> e.startsWith('P') })//-1
println(languageSet.indexOfLast { e -> e.endsWith('+') })//2
println(languageSet.find { e -> e.startsWith('C') }) // C
println(languageSet.find { e -> e.startsWith('P') }) // null
println(languageSet.findLast { e -> e.endsWith('+') }) // C++
Mathematical functions of Set
The below example show how to use:
- max() : returns the largest element or `null` if there are no elements.
- min() : returns the smallest element or `null` if there are no elements.
- sum() : returns the sum of all elements in the set.
- average() : returns an average value of elements in the set.
- union : returns a set containing all distinct elements from both sets.
- intersect : returns a set containing all common elements of both sets.
- subtract : remove all the elements of specified set from the given set (if element exist).
val numSet = setOf<Int>(1, 2, 3)
println("Max element in set: ${numSet.max()}")
//Max element in set: 3
println("Min element in set: ${numSet.min()}")
//Min element in set: 1
println("Sum of elements in set: ${numSet.sum()}")
//Sum of elements in set: 6
println("Average of elements in set: ${numSet.average()}")
//Average of elements in set: 2.0
println(numSet union setOf(4, 5))
//[1, 2, 3, 4, 5]
println(setOf(6) union numSet)
//[6, 1, 2, 3]
println(numSet intersect setOf(2, 5)) //[2]
println(numSet subtract setOf(2, 3)) //[1]
Kotlin Mutable Set
MutableSet inherits Set and supports read/write access, you can add, update or remove items.
MutableSet are created using mutableSetOf() and mutableSetOf()<T>() functions.
Create and initialize mutableSet
The below example show you how to:
- initialize MutableSet using mutableSetOf() (contains elements of all type), mutableSetOf()<T>() (contains elements of specific type).
- create new MutableSet from another MutableSet with the same elements using toMutableSet() function.
fun main() {
val set1 = mutableSetOf("Arun", 10, 1.05f, 'a', null, 10)
val set2 = mutableSetOf<String>("Arun", "Neha", "Monika")
val set3 = set2.toMutableSet()
println(set1) //[Arun, 10, 1.05, a, null]
println(set2) //[Arun, Neha, Monika]
println(set3) //[Arun, Neha, Monika]
}
MutableSet specific functions
The below example show you how to use:
- add(element): adds the specified element to the set. Returns true if the element has been added, false if the element is already contained in the set.
- addAll(): adds all of the elements of the specified set to this set.
- remove(element): removes element from set.
- removeAll(): removes all of this set’s elements that are also contained in the specified set.
- retainAll(): retains only the elements defined in this set that are contained in the specified set.
- clear(): removes all elements of the set.
fun main() {
val languages = mutableSetOf<String>("Kotlin", "Java", "Kotlin")
println(languages) //[Kotlin, Java]
languages.add("Angular")
println(languages) //[Kotlin, Java, Angular]
languages.addAll(setOf("C++", "C"))
println(languages) //[Kotlin, Java, Angular, C++, C]
languages.remove("Java")
println(languages) //[Kotlin, Angular, C++, C]
languages.removeAll(setOf("Angular"))
println(languages) //[Kotlin, C++, C]
languages.retainAll(setOf("C++", "C"))
println(languages) //[C++, C]
languages.clear() //[]
println(languages)
}
Iterate over Set in Kotlin
The examples show you how to iterate over a Set using:
- forEach() method.
- simple for loop
- for loop with item index
- forEachIndexed() that gives us index and value in each iteration.
- Iterator and a while loop.
fun main() { val numSet = setOf(1, 5, 7, 8) print("print list using forEach method: ") numSet.forEach { e -> print("$e, ") } println() print("print list using for loop: ") for (word in numSet) { print("$word, ") } println() print("for loop with item index: ") for (i in 0 until numSet.size) { print("${numSet.elementAt(i)}, ") } println() println("print list using forEachIndexed() : ") numSet.forEachIndexed({ i, e -> println("$i - $e") })
print("print list using Iterator: ") val it: Iterator<Int> = numSet.iterator() while (it.hasNext()) { val e = it.next() print("$e, ") } println()
}
Output:
print list using forEach method: 1, 5, 7, 8,
print list using for loop: 1, 5, 7, 8,
for loop with item index: 1, 5, 7, 8,
print list using forEachIndexed():
0 - 1
1 - 5
2 - 7
3 - 8
print list using Iterator: 1, 5, 7, 8,