How to convert String array to Int array in Kotlin

2019-01-27 13:42发布

问题:

Kotlin has many shorthands and interesting features. So, I wonder if there is some fast and short way of converting array of string to array of integers. Similar to this code in Python:

results = [int(i) for i in results]

回答1:

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 over arrays in non-performance-critical code, see the differences.

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



回答2:

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

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

This version is compiled to a basic for 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;
}


回答3:

I'd use something simple like

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

Alternatively, if you're into extensions:

fun Array<String>.asInts() = this.map { it.toInt() }.toTypedArray()

strings.asInts()