From
val array = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4)
I need to convert to ArrayList<Int>
I have tried array.toTypedArray()
But it converted to Array<Int>
instead
Constructors – 1) ArrayList<E>(): – Creates an empty ArrayList 2) ArrayList(capacity: Int): – Creates an ArrayList of specified size. 3) ArrayList(elements: Collection<E>): – Create an ArrayList filled by collection elements.
Kotlin Array. Array is a collection of similar data either of types Int, String etc. Array in Kotlin has mutable in nature with fixed size.
We can insert an item to an ArrayList using the add() function provided by the Kotlin library. In this example, we will be creating two lists: one is "myMutableList" which is a collection of mutable data types, and the other one is "myImmutableList" which is a collection of immutable data types.
This article explores different ways to convert a String Array to an Int Array in Kotlin. 1. Using map () function The standard solution is to use the map { … } with toInt () or toIntOrNull () function to convert each string in the string array to an integer.
To convert the list to an array, first we created a string array named array with size equals to list.size(). Then, we simply used list's toArray() method to convert the list items to array items.
Another solution is to convert the specified IntArrayto a list using the toList()function. Then, we can call toTypedArray()function to get an Array<Int>. 1 2 3 4
To convert the array list to an array, we have used the toTypedArray () method. Finally, the elements of the array are printed by using the forEach () loop. To convert an array to an array list, we have used the toList () method. Here's the equivalent Java code: Java program to convert list to array and vice-versa.
You can use toCollection
function and specify ArrayList
as a mutable collection to fill:
val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
You can get List<Int>
with a simple toList
call like so:
val list = intArrayOf(5, 3, 0, 2).toList()
However if you really need ArrayList
you can create it too:
val list = arrayListOf(*intArrayOf(5, 3, 0, 2).toTypedArray())
or using more idiomatic Kotlin API as suggested by @Ilya:
val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
Or if you'd like to do the above yourself and save some allocations:
val arrayList = intArrayOf(5, 3, 0, 2).let { intList ->
ArrayList<Int>(intList.size).apply { intList.forEach { add(it) } }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With