How to convert intArray to ArrayList <Int> in Kotlin?

WITH

val array = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4)

I need to convert to ArrayList<Int>

I tried array.toTypedArray()

But instead, it is converted to Array<Int>

+4
source share
2 answers

You can use toCollectionand specify ArrayListas mutable collection:

val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
+8
source

You can get List<Int>simple toListas follows:

val list = intArrayOf(5, 3, 0, 2).toList()

However, if you really need to ArrayList, you can also create it:

val list = arrayListOf(*intArrayOf(5, 3, 0, 2).toTypedArray())

or using the more idiomatic Kotlin API, as suggested by @Ilya :

val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())

Or, if you want to do it higher and keep some distributions:

val arrayList = intArrayOf(5, 3, 0, 2).let { intList ->
    ArrayList<Int>(intList.size).apply { intList.forEach { add(it) } }
}
+8
source

Source: https://habr.com/ru/post/1657713/


All Articles