The syntax of Map.map() extension function is:
fun <K, V, R> Map<out K, V>.map( transform: (Entry<K, V>) -> R ): List<R>
This map() extension function of Map returns a list containing the results of applying the given transform function to each entry in the original map.
In this example,
map1
with key-value pairs.map
function on map1
, applying a transform function that concatenates each key-value pair into a string.fun main(args: Array<String>) {
val map1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
val result1 = map1.map { (key, value) -> "Key: $key, Value: $value" }
println(result1)
}
[Key: key1, Value: 1, Key: key2, Value: 2, Key: key3, Value: 3]
In this example,
map2
with key-value pairs.map
function on map2
, applying a transform function that extracts only the values into a string.fun main(args: Array<String>) {
val map2 = mapOf(1 to "one", 2 to "two", 3 to "three")
val result2 = map2.map { (key, value) -> "Value: $value" }
println(result2)
}
[Value: one, Value: two, Value: three]
In this example,
map3
with key-value pairs.map
function on map3
, applying a transform function that converts each key to uppercase.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
val result3 = map3.map { (key, value) -> key.toUpperCase() }
println(result3)
}
[APPLE, BANANA, CHERRY]
In this Kotlin tutorial, we learned about map() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.