Kotlin Set toList()
Syntax & Examples
Set.toList() extension function
The toList() extension function in Kotlin returns a List containing all elements of the collection.
Syntax of Set.toList()
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.
Return Type
Set.toList() returns value of type List
.
✐ Examples
1 Converting a set of integers to a list
Using toList() to convert a set of integers to a list.
For example,
- Create a set of integers.
- Use toList() to convert the set to a list.
- Print the resulting list.
Kotlin Program
fun main() {
val intSet = setOf(1, 2, 3)
val intList = intSet.toList()
println(intList)
}
Output
[1, 2, 3]
2 Converting a set of strings to a list
Using toList() to convert a set of strings to a list.
For example,
- Create a set of strings.
- Use toList() to convert the set to a list.
- Print the resulting list.
Kotlin Program
fun main() {
val stringSet = setOf("one", "two", "three")
val stringList = stringSet.toList()
println(stringList)
}
Output
[one, two, three]
3 Converting a set of custom objects to a list
Using toList() to convert a set of custom objects to a list.
For example,
- Create a data class.
- Create a set of custom objects.
- Use toList() to convert the set to a list.
- Print the resulting list.
Kotlin Program
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)
}
Output
[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
Summary
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.