Kotlin Map mapKeys()
Syntax & Examples
Syntax of Map.mapKeys()
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.
✐ Examples
1 Map keys to their lengths
In this example,
- We create a map named
map1
with key-value pairs. - We use the
mapKeys()
function to transform the keys ofmap1
by their lengths. - The resulting map
transformedMap
has keys representing the lengths of the original keys inmap1
. - We print the transformed map to standard output.
Kotlin Program
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)
}
Output
{5=1, 6=3}
2 Map keys to uppercase
In this example,
- We create a map named
map2
with key-value pairs. - We use the
mapKeys()
function to transform the keys ofmap2
to uppercase. - The resulting map
transformedMap
has keys that are the uppercase versions of the original keys inmap2
. - We print the transformed map to standard output.
Kotlin Program
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)
}
Output
{APPLE=1, BANANA=2, CHERRY=3}
3 Map keys to their values
In this example,
- We create a map named
map3
with key-value pairs. - We use the
mapKeys()
function to transform the keys ofmap3
to their corresponding values. - The resulting map
transformedMap
has keys that are the values of the original mapmap3
. - We print the transformed map to standard output.
Kotlin Program
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)
}
Output
{1=1, 2=2, 3=3}
Summary
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.