The syntax of Map.mapKeys() extension function is:
fun <K, V, R> Map<out K, V>.mapKeys( transform: (Entry<K, V>) -> R ): Map<R, V>
This mapKeys() extension function of Map returns a new 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.mapKeys()
function to transform the keys of map1
by their lengths.transformedMap
has keys representing the lengths of the original keys in map1
.fun main(args: Array<String>) {
val map1 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val transformedMap = map1.mapKeys { entry -> entry.key.length }
println(transformedMap)
}
{5=1, 6=3}
In this example,
map2
with key-value pairs.mapKeys()
function to transform the keys of map2
to uppercase.transformedMap
has keys that are the uppercase versions of the original keys in map2
.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val transformedMap = map2.mapKeys { entry -> entry.key.toUpperCase() }
println(transformedMap)
}
{APPLE=1, BANANA=2, CHERRY=3}
In this example,
map3
with key-value pairs.mapKeys()
function to transform the keys of map3
to their corresponding values.transformedMap
has keys that are the values of the original map map3
.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val transformedMap = map3.mapKeys { entry -> entry.value }
println(transformedMap)
}
{1=1, 2=2, 3=3}
In this Kotlin tutorial, we learned about mapKeys() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.