In Kotlin, you can convert a set of strings to a set of integers by iterating over each element of the string set and converting it to an integer using the toInt()
method or Integer.parseInt()
function.
In this example,
stringSet1
containing the elements "1", "2", "3", "4", "5"
.intSet1
.stringSet1
using a forEach
loop.toInt()
method and add it to the intSet1
.intSet1
to standard output.fun main() {
val stringSet1 = setOf("1", "2", "3", "4", "5")
val intSet1 = mutableSetOf<Int>()
stringSet1.forEach {
intSet1.add(it.toInt())
}
println("Converted int set: $intSet1")
}
Converted int set: [1, 2, 3, 4, 5]
In this example,
stringSet2
containing the elements "10", "20", "30", "40", "50"
.intSet2
.stringSet2
using a forEach
loop.Integer.parseInt()
function and add it to the intSet2
.intSet2
to standard output.fun main() {
val stringSet2 = setOf("10", "20", "30", "40", "50")
val intSet2 = mutableSetOf<Int>()
stringSet2.forEach {
intSet2.add(Integer.parseInt(it))
}
println("Converted int set: $intSet2")
}
Converted int set: [10, 20, 30, 40, 50]
In this tutorial, we learned How to Convert a Set of Strings to a Set of Integers in Kotlin language with well detailed examples.