The toList() extension function in Kotlin returns a List containing all elements of the collection.
The syntax of Set.toList() extension function is:
fun <T> Set<T>.toList(): List<T>
This toList() extension function of Set returns a List containing all elements.
Set.toList() returns value of type List
.
Using toList() to convert a set of integers to a list.
For example,
fun main() {
val intSet = setOf(1, 2, 3)
val intList = intSet.toList()
println(intList)
}
[1, 2, 3]
Using toList() to convert a set of strings to a list.
For example,
fun main() {
val stringSet = setOf("one", "two", "three")
val stringList = stringSet.toList()
println(stringList)
}
[one, two, three]
Using toList() to convert a set of custom objects to a list.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val peopleSet = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val peopleList = peopleSet.toList()
println(peopleList)
}
[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about toList() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.