How to convert a String array to an Int array in Kotlin?

Kotlin has many abbreviations and interesting features. So I'm wondering if there is a quick and short way to convert a string array to an array of integers. Like this code in Python:

results = [int(i) for i in results] 
+16
arrays type-conversion kotlin
source share
4 answers

You can use .map { ... } with .toInt() or .toIntOrNull() :

 val result = strings.map { it.toInt() } 

Only the result is not an array, but a list. It is preferable to use lists by arrays in code that is critical for inactivity, see the differences .

If you need an array, add .toTypedArray() or .toIntArray() .

+39
source share

If you are trying to transform a List structure that implements RandomAccess (e.g. ArrayList or Array ), you can use this version for better performance:

 IntArray(strings.size) { strings[it].toInt() } 

This version is compiled for the base loop and int[] :

 int size = strings.size(); int[] result = new int[size]; int index = 0; for(int newLength = result.length; index < newLength; ++index) { String numberRaw = strings.get(index); int parsedNumber = Integer.parseInt(numberRaw); result[index] = parsedNumber; } 
+2
source share
 val result = "[1, 2, 3, 4, 5]".removeSurrounding("[","]").replace(" ","").split(",").map { it.toInt() } 
+2
source share

I would use something simple like

 val strings = arrayOf("1", "2", "3") val ints = ints.map { it.toInt() }.toTypedArray() 

Also, if you use extensions:

 fun Array<String>.asInts() = this.map { it.toInt() }.toTypedArray() strings.asInts() 
+1
source share

All Articles