To convert a set of strings to a set of floats in Kotlin, you can use the mapNotNull()
function along with the toFloatOrNull()
function to transform each string value into its corresponding float value.
In this example,
stringSet1
with values ["1.1", "2.2", "3.3"]
.mapNotNull()
function on stringSet1
to transform each string value into its corresponding float value. We pass a lambda function to mapNotNull()
that attempts to convert each string value to a float using the toFloatOrNull()
function.mapNotNull()
function returns a list of non-null float values. We convert this list into a set of floats using the toSet()
function.fun main() {
val stringSet1 = setOf("1.1", "2.2", "3.3")
val floatSet1 = stringSet1.mapNotNull { it.toFloatOrNull() }.toSet()
println(floatSet1)
}
{1.1, 2.2, 3.3}
In this example,
stringSet2
with values ["4.5", "5.6", "6.7"]
.mapNotNull()
function on stringSet2
to transform each string value into its corresponding float value. We pass a lambda function to mapNotNull()
that attempts to convert each string value to a float using the toFloatOrNull()
function.mapNotNull()
function returns a list of non-null float values. We convert this list into a set of floats using the toSet()
function.fun main() {
val stringSet2 = setOf("4.5", "5.6", "6.7")
val floatSet2 = stringSet2.mapNotNull { it.toFloatOrNull() }.toSet()
println(floatSet2)
}
{4.5, 5.6, 6.7}
In this tutorial, we learned How to Convert a Set of Strings to a Set of Floats in Kotlin language with well detailed examples.