Kotlin Tutorials

Kotlin Map map()
Syntax & Examples

Syntax of Map.map()

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.



✐ Examples

1 Transform map entries into strings with keys and values

In this example,

  • We create a map named map1 with key-value pairs.
  • We use the map function on map1, applying a transform function that concatenates each key-value pair into a string.
  • As a result, a list of transformed strings is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

[Key: key1, Value: 1, Key: key2, Value: 2, Key: key3, Value: 3]

2 Transform map entries into strings with values only

In this example,

  • We create a map named map2 with key-value pairs.
  • We use the map function on map2, applying a transform function that extracts only the values into a string.
  • As a result, a list of transformed strings is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

[Value: one, Value: two, Value: three]

3 Transform map keys into uppercase strings

In this example,

  • We create a map named map3 with key-value pairs.
  • We use the map function on map3, applying a transform function that converts each key to uppercase.
  • As a result, a list of transformed uppercase keys is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

[APPLE, BANANA, CHERRY]

Summary

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.