Kotlin Tutorials

Kotlin Map mapValuesTo()
Syntax & Examples

Syntax of Map.mapValuesTo()

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.



✐ Examples

1 Map values to strings

In this example,

  • We create a map named map1 with integer keys and string values.
  • We initialize an empty mutable map named destination.
  • We use the mapValuesTo() function to apply a transformation to each value in map1, adding a prefix Value: to each value.
  • The transformed entries are populated into the destination map.
  • We print the destination map to standard output.

Kotlin Program

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

Output

{1=Value: apple, 2=Value: banana, 3=Value: cherry}

2 Replace null values with 0

In this example,

  • We create a map named map2 with string keys and nullable integer values.
  • We initialize an empty mutable map named destination.
  • We use the mapValuesTo() function to apply a transformation to each value in map2, replacing null values with 0.
  • The transformed entries are populated into the destination map.
  • We print the destination map to standard output.

Kotlin Program

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

Output

{apple=1, banana=2, cherry=3}

3 Double the values

In this example,

  • We create a map named map3 with string keys and integer values.
  • We initialize an empty mutable map named destination.
  • We use the mapValuesTo() function to apply a transformation to each value in map3, doubling each value.
  • The transformed entries are populated into the destination map.
  • We print the destination map to standard output.

Kotlin Program

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

Output

{apple=2, banana=4, cherry=6}

Summary

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.