2

I am looking to convert an List<String> to an List<Int> in Kotlin.

val stringArray = "1 2 3 4 5 6".split(" ")
val intArray = MutableList<Int>(0, {0})
for (item in stringArray) {
    intArray.add(item.toInt())
}

The above will do it, but it feels as if there is a better way of doing this (possible with lambdas and streams?).

1

3 Answers 3

8

If your input really has delimiters, you can split as already suggested. Afterwards map is what you need. This will do the trick:

val numbers = "1 2 3 4 5 6"
val result = numbers.split(" ").map(String::toInt)
Sign up to request clarification or add additional context in comments.

Comments

4
val intArray = stringArray.map(String::toInt)

or with lambda

val intArray = stringArray.map { it.toInt() }

2 Comments

Great answers. But can you expand how they are different?
They do the same with your array, it's just the type of parameter which defers: in the first example a method reference, in the second a lambda is passed to map
2

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

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.