Converting a Kotlin List to a Set
List.toSet()
You can convert a List to a Set by using the List.toSet() function.
fun main() {
val list = listOf(1, 2, 3, 4, 5)
val set = list.toSet()
println(set)
}
Output:
[1, 2, 3, 4, 5]
MutableList.toMutableSet()
The List.toMutableSet() function returns a Set that can add elements. In the example below, the add() function is used to add an element to set.
fun main() {
val list = mutableListOf(1, 2, 3, 4, 5)
val set = list.toMutableSet()
set.add(6)
println(set)
}
Output:
[1, 2, 3, 4, 5, 6]
HashSet()
You can also convert to a Set by passing list to the HashSet() constructor function.
fun main() {
val list = listOf(1, 2, 3, 4, 5)
val set = HashSet(list)
println(set)
}
Output:
[1, 2, 3, 4, 5]
Set.addAll()
You can also add the elements of list to a set declared as MutableSet by using the addAll() function.
fun main() {
val list = listOf(1, 2, 3, 4, 5)
val set: MutableSet<Int> = HashSet()
set.addAll(list)
println(set)
}
Output:
[1, 2, 3, 4, 5]