Convert a list to an array in Kotlin
This article explores different ways to convert a list to an array in Kotlin.
1. Using toTypedArray()
function
List
interface provides a toTypedArray()
function that returns a typed array containing the list elements.
1 2 3 4 5 6 7 |
fun main() { val list: List<Int> = listOf(1, 2, 3, 4, 5) val array: Array<Int> = list.toTypedArray() println(array.contentToString()) // [1, 2, 3, 4, 5] } |
To convert between two types, you can use the map()
function. For example, the following code converts from a list of Integer to an array of String:
1 2 3 4 5 6 7 |
fun main() { val list: List<Int> = listOf(1, 2, 3, 4, 5) val array: Array<String> = list.map { it.toString() }.toTypedArray() println(array.contentToString()) // [1, 2, 3, 4, 5] } |
2. Using Java 8 Stream
You can also use Stream to convert a list to an array. The trick is to convert the given list to Stream using the stream()
function and use the toArray()
function to return an array containing the Stream elements. The conversion between the two types can be done using a lambda expression.
1 2 3 4 5 6 7 |
fun main() { val list: List<Int> = listOf(1, 2, 3, 4, 5) val array: Array<Int> = list.stream().toArray { arrayOfNulls<Int>(it) } println(array.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about converting a list 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 :)