30

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]
0

7 Answers 7

75

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().

Sign up to request clarification or add additional context in comments.

Comments

4

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()

Comments

3

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;
}

Comments

3

If you use Array.map as other answers suggest, you get back a List, not an Array. If you want to map an array strings to another array results, you can do it directly like this:

val results = Array(strings.size) { strings[it].toInt() }

This is more efficient than first mapping to a List and then copying the elements over to an Array by calling .toTypedArray().

Comments

1

Consider the input like this "" (empty string)

It would be better to do the filtering first. And it is true the return value is list but not array.

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

    fun stringToIntList(data: String): List<Int> =
            data.split(",").filter { it.toIntOrNull() != null }
                    .map { it.toInt() }

Comments

0
val result = "[1, 2, 3, 4, 5]".removeSurrounding("[","]").replace(" ","").split(",").map { it.toInt() }

3 Comments

The "[" and "," handling code is completely unnecessary here.
@AndrewRegan would you care to give full reasons, why?
@RowlandMtetezi, because it is distracting, and question does not contain it.
0

Found following simplest

strings.chars().toArray()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.