In this tutorial, you shall learn how to convert a given list into a Set in Kotlin using List.toSet() function, with examples.

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

ADVERTISEMENT

1. Convert list of numbers to a Set

In the following example, we will take a list of integers in myList, and convert this list into a Set.

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]

2. Convert list of numbers to a Set, when the list has duplicates

If the given list has duplicate elements, then only those elements that are unique will make it to the resulting Set.

Main.kt

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

Output

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

Conclusion

In this Kotlin Tutorial, we learned how to convert a given list into a set in Kotlin, with the help of examples.