Convert a set to an array in Kotlin
This article explores different ways to convert a set to an array in Kotlin.
1. Using toTypedArray() function
The Set interface has the toTypedArray() function, which returns a Typed Array containing the set elements.
|
1 2 3 4 5 6 7 |
fun main() { val set: Set<Int> = setOf(1, 2, 3, 4, 5) val array: Array<Int> = set.toTypedArray() println(array.contentToString()) // [1, 2, 3, 4, 5] } |
To return a primitive int array from Set of Integer, you can call the toIntArray() function.
|
1 2 3 4 5 6 |
fun main() { val ints: Set<Int> = mutableSetOf(1, 2, 3, 4, 5) val primitive: IntArray = ints.toIntArray() println(primitive.contentToString()) // [1, 2, 3, 4, 5] } |
2. Using Java 8 Stream
Another solution is to use Stream to convert the Set into an array. The idea is to use the toArray() function, which returns an array containing the Stream elements.
|
1 2 3 4 5 6 7 |
fun main() { val set: Set<Int> = setOf(1, 2, 3, 4, 5) val array: Array<Int> = set.stream().toArray { arrayOfNulls<Int>(it) } println(array.contentToString()) // [1, 2, 3, 4, 5] } |
3. Using for loop
Alternatively, you can iterate over the given set and assign each encountered element to the array one by one.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val set: Set<Int> = setOf(1, 2, 3, 4, 5) val array = arrayOfNulls<Int>(set.size) var k = 0 for (item in set) { array[k++] = item } println(array.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about converting a set to an array 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 :)