Convert IntArray to Integer List in Kotlin
This article explores different ways to convert an IntArray to a list of Integer using Kotlin.
1. Using toList() function
The standard way to convert an array to a list is with toList() or toMutableList() function. The toList() function creates an immutable list, while toMutableList() function creates a mutable list.
|
1 2 3 4 5 6 7 |
fun main() { val arr: IntArray = IntArray(5) { it + 1 } val list: MutableList<Int> = arr.toMutableList() println(list) // [1, 2, 3, 4, 5] } |
2. Using toCollection() function
You can also specify the List implementation of your choice using the toCollection() function. This is demonstrated below:
|
1 2 3 4 5 6 7 |
fun main() { val arr: IntArray = IntArray(5) { it + 1 } val list: MutableList<Int> = arr.toCollection(ArrayList()) println(list) // [1, 2, 3, 4, 5] } |
3. Using listOf() function
You can also use the listOf() or mutableListOf() function. But first, you need to convert the primitive array to the typed array and prefix it with * (Spread operator).
|
1 2 3 4 5 6 7 |
fun main() { val arr: IntArray = IntArray(5) { it + 1 } val list: MutableList<Int> = mutableListOf(*arr.toTypedArray()) println(list) // [1, 2, 3, 4, 5] } |
4. Custom Routine
Finally, you can write your own logic for this task. The idea is to use a foreach loop to add elements from the IntArray array to a mutable list.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val arr: IntArray = IntArray(5) { it + 1 } val list: MutableList<Int> = ArrayList(arr.size) for (i in arr) { list.add(i) } println(list) // [1, 2, 3, 4, 5] } |
That’s all about converting IntArray to Integer 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 :)