Kotlin – Convert List to Set

To convert List to Set in Kotlin, call toSet() on this list. toSet() returns a new Set created with the elements of this List.

The syntax to call toSet() function on this List myList is

myList.toSet()

Examples

In the following example, we will take a List, and convert this List to a Set using toSet() function.

Main.kt

fun main(args: Array<String>) {
    var myList = listOf(1, 4, 9, 16, 25)
    var mySet = myList.toSet()
    println("Set : ${mySet}")
}

Output

Set : [1, 4, 9, 16, 25]

Conclusion

In this Kotlin Tutorial, we learned how to create a Set of Strings in Kotlin, using setOf() or mutableSetOf() functions, with the help of examples.