Kotlin Tutorials

Kotlin Map mapKeysTo()
Syntax & Examples

Syntax of Map.mapKeysTo()

The syntax of Map.mapKeysTo() extension function is:

fun <K, V, R, M : MutableMap<in R, in V>> Map<out K, V>.mapKeysTo( destination: M, transform: (Entry<K, V>) -> R ): M

This mapKeysTo() extension function of Map populates the given destination map with entries having the keys obtained by applying the transform function to each entry in this Map and the values of this map.



✐ Examples

1 Transform map keys to uppercase and populate destination map

In this example,

  • We create a map named map1 with key-value pairs.
  • We create an empty mutable destination map.
  • We use the mapKeysTo function on map1, applying a transform function that converts each key to uppercase.
  • The transformed keys and original values are populated into the destination map.
  • We print the destination map to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
    val destinationMap1 = mutableMapOf<String, Int>()
    map1.mapKeysTo(destinationMap1) { (key, _) -> key.toUpperCase() }
    println(destinationMap1)
}

Output

{KEY1=1, KEY2=2, KEY3=3}

2 Copy map values to a new destination map

In this example,

  • We create a map named map2 with key-value pairs.
  • We create an empty mutable destination map.
  • We use the mapKeysTo function on map2, applying a transform function that extracts each value.
  • The transformed values and original keys 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 5, "banana" to 6, "cherry" to 7)
    val destinationMap2 = mutableMapOf<Int, Int>()
    map2.mapKeysTo(destinationMap2) { (_, value) -> value }
    println(destinationMap2)
}

Output

{5=5, 6=6, 7=7}

3 Transform map keys to strings and populate destination map

In this example,

  • We create a map named map3 with key-value pairs.
  • We create an empty mutable destination map.
  • We use the mapKeysTo function on map3, applying a transform function that converts each key to a string.
  • The transformed keys and original values are populated into the destination map.
  • We print the destination map to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf(1 to "one", 2 to "two", 3 to "three")
    val destinationMap3 = mutableMapOf<String, String>()
    map3.mapKeysTo(destinationMap3) { (key, _) -> key.toString() }
    println(destinationMap3)
}

Output

{1=one, 2=two, 3=three}

Summary

In this Kotlin tutorial, we learned about mapKeysTo() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.