Convert Integer List to IntArray in Kotlin
This article explores different ways to convert List of Integer to IntArray in Kotlin.
To convert a list of integers to an array of int, you can use the toIntArray() function.
|
1 2 3 4 5 6 |
fun main() { val list = listOf(1, 2, 3, 4, 5) val primitive = list.toIntArray() println(primitive.contentToString()) // [1, 2, 3, 4, 5] } |
If your list contains the null values, you need to filter out the null values first. This can be done using the filterNotNull() function.
|
1 2 3 4 5 6 7 |
fun main() { val list = listOf(1, 2, 3, 4, null, 5) val primitive = list.filterNotNull().toIntArray() println(primitive.contentToString()) // [1, 2, 3, 4, 5] } |
Alternatively, you can handle the null inside the lambda expression, as shown below:
|
1 2 3 4 5 6 7 |
fun main() { val list = listOf(1, 2, 3, 4, null, 5) val primitive = list.map { i: Int? -> i ?: 0 }.toIntArray() println(primitive.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about converting an Integer list to IntArray 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 :)