Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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]
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()
.
Alternatively, if you're into extensions:
fun Array<String>.asInts() = this.map { it.toInt() }.toTypedArray()
strings.asInts()
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;
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()
.
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() }
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.