To convert an array of strings to an array of integers in Kotlin, you can use the map
function combined with the toInt
method.
In this example,
stringArray
with numerical string values.map
function on stringArray
to transform each string element into an integer. The map
function applies the toInt
method to each element of the array.map
function is a list of integers, which we convert to an array using the toTypedArray
method.fun main(args: Array<String>) {
val stringArray = arrayOf("1", "2", "3", "4", "5")
val intArray = stringArray.map { it.toInt() }.toTypedArray()
println("Converted array: ${intArray.joinToString()}")
}
Converted array: 1, 2, 3, 4, 5
In this example,
stringArray
with both numerical and non-numerical string values.mapNotNull
function on stringArray
to transform each string element into an integer, ignoring any non-numeric values. The mapNotNull
function applies the toIntOrNull
method to each element, which returns null for non-numeric values.mapNotNull
function is a list of integers, which we convert to an array using the toTypedArray
method.fun main(args: Array<String>) {
val stringArray = arrayOf("1", "two", "3", "four", "5")
val intArray = stringArray.mapNotNull { it.toIntOrNull() }.toTypedArray()
println("Converted array: ${intArray.joinToString()}")
}
Converted array: 1, 3, 5
In this tutorial, we learned How to Convert an Array of Strings to an Array of Integers in Kotlin language with well detailed examples.