Convert a Set to a List in Kotlin
This article explores different ways to convert a set to a list using Kotlin.
1. Using toList() function
The standard way to convert a set to a list is using the toList() function.
|
1 2 3 4 5 6 7 |
fun main() { val set: Set<String> = setOf("A", "B", "C") val list: List<String> = set.toList() println(list) // [A, B, C] } |
It returns an immutable list instance. To get a mutable list, you can use the toMutableList() function.
|
1 2 3 4 5 6 7 |
fun main() { val set: MutableSet<String> = mutableSetOf("A", "B", "C") val list: MutableList<String> = set.toMutableList() println(list) // [A, B, C] } |
2. Using Copy Constructor
We can use a copy constructor, which can take another collection object to construct a new list containing all elements of the specified set.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> convert(set: Set<T>): List<T> { return ArrayList(set) } fun main() { val set: Set<String> = setOf("A", "B", "C") val list: List<String> = convert(set) println(list) // [A, B, C] } |
3. Using Spread Operator
You can also use the listOf() function using the Spread operator by prefixing its array implementation with *.
|
1 2 3 4 5 6 7 |
fun main() { val set: Set<String> = setOf("A", "B", "C") val list: List<String> = listOf(*set.toTypedArray()) println(list) // [A, B, C] } |
4. Using for loop
Another solution is to create an empty list and push every element of the specified Set into the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun <T> convert(set: Set<T>): List<T> { val list: MutableList<T> = ArrayList() for (i in set) { list.add(i) } return list } fun main() { val set: Set<String> = setOf("A", "B", "C") val list: List<String> = convert(set) println(list) // [A, B, C] } |
5. Using addAll() function
Instead of using the for-loop, you can use the addAll() to add all elements of the specified Set to the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <T> convert(set: Set<T>): List<T> { val list: MutableList<T> = ArrayList() list.addAll(set); return list } fun main() { val set: Set<String> = setOf("A", "B", "C") val list: List<String> = convert(set) println(list) // [A, B, C] } |
That’s all about converting a set to a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)