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.
In this example,
map1
with key-value pairs.mapKeysTo
function on map1
, applying a transform function that converts each key to uppercase.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)
}
{KEY1=1, KEY2=2, KEY3=3}
In this example,
map2
with key-value pairs.mapKeysTo
function on map2
, applying a transform function that extracts each value.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)
}
{5=5, 6=6, 7=7}
In this example,
map3
with key-value pairs.mapKeysTo
function on map3
, applying a transform function that converts each key to a string.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)
}
{1=one, 2=two, 3=three}
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.