Kotlin Tutorials

Kotlin Map mapValues()
Syntax & Examples

Syntax of Map.mapValues()

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.



✐ Examples

1 Double the values in the map

In this example,

  • We create a map named map1 with key-value pairs.
  • We use the mapValues function on map1, applying a transform function that doubles each value.
  • The resulting map contains the same keys but with doubled values.
  • We print the resulting map to standard output.

Kotlin Program

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)
}

Output

{key1=2, key2=4, key3=6}

2 Concatenate keys and values in the map

In this example,

  • We create a map named map2 with key-value pairs.
  • We use the mapValues function on map2, applying a transform function that concatenates each key with its corresponding value.
  • The resulting map contains keys concatenated with their values.
  • We print the resulting map to standard output.

Kotlin Program

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)
}

Output

{apple=apple1, banana=banana2, cherry=cherry3}

3 Calculate sum of key lengths and values in the map

In this example,

  • We create a map named map3 with key-value pairs.
  • We use the mapValues function on map3, applying a transform function that calculates the sum of the key's length and its corresponding value.
  • The resulting map contains keys mapped to the sum of their lengths and values.
  • We print the resulting map to standard output.

Kotlin Program

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)
}

Output

{one=4, two=5, three=8}

Summary

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.