The syntax of Map.mapValuesTo() extension function is:
fun <K, V, R, M : MutableMap<in K, in R>> Map<out K, V>.mapValuesTo( destination: M, transform: (Entry<K, V>) -> R ): M
This mapValuesTo() extension function of Map populates the given destination map with entries having the keys of this map and the values obtained by applying the transform function to each entry in this Map.
In this example,
map1
with integer keys and string values.destination
.mapValuesTo()
function to apply a transformation to each value in map1
, adding a prefix Value:
to each value.destination
map.destination
map to standard output.fun main(args: Array<String>) {
val map1 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry")
val destination = mutableMapOf<Int, String>()
map1.mapValuesTo(destination) { entry -> "Value: ${entry.value}" }
println(destination)
}
{1=Value: apple, 2=Value: banana, 3=Value: cherry}
In this example,
map2
with string keys and nullable integer values.destination
.mapValuesTo()
function to apply a transformation to each value in map2
, replacing null values with 0.destination
map.destination
map to standard output.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val destination = mutableMapOf<String, Int>()
map2.mapValuesTo(destination) { entry -> entry.value ?: 0 }
println(destination)
}
{apple=1, banana=2, cherry=3}
In this example,
map3
with string keys and integer values.destination
.mapValuesTo()
function to apply a transformation to each value in map3
, doubling each value.destination
map.destination
map to standard output.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val destination = mutableMapOf<String, Int>()
map3.mapValuesTo(destination) { entry -> entry.value * 2 }
println(destination)
}
{apple=2, banana=4, cherry=6}
In this Kotlin tutorial, we learned about mapValuesTo() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.