The syntax of Map.mapValues() extension function is:
fun <K, V, R> Map<out K, V>.mapValues( transform: (Entry<K, V>) -> R ): Map<K, R>
This mapValues() extension function of Map returns a new 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 key-value pairs.mapValues
function on map1
, applying a transform function that doubles each value.fun main(args: Array<String>) {
val map1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
val result = map1.mapValues { (key, value) -> value * 2 }
println(result)
}
{key1=2, key2=4, key3=6}
In this example,
map2
with key-value pairs.mapValues
function on map2
, applying a transform function that concatenates each key with its corresponding value.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val result = map2.mapValues { (key, value) -> key + value }
println(result)
}
{apple=apple1, banana=banana2, cherry=cherry3}
In this example,
map3
with key-value pairs.mapValues
function on map3
, applying a transform function that calculates the sum of the key's length and its corresponding value.fun main(args: Array<String>) {
val map3 = mapOf("one" to 1, "two" to 2, "three" to 3)
val result = map3.mapValues { (key, value) -> key.length + value }
println(result)
}
{one=4, two=5, three=8}
In this Kotlin tutorial, we learned about mapValues() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.