Kotlin Tutorials

Kotlin Map forEach()
Syntax & Examples

Syntax of Map.forEach()

The syntax of Map.forEach() extension function is:

fun <K, V> Map<out K, V>.forEach( action: (Entry<K, V>) -> Unit)

This forEach() extension function of Map performs the given action on each entry.



✐ Examples

1 Print key-value pairs of a map of strings

In this example,

  • We create a map where keys are integers and values are strings.
  • We use the forEach function on the map, applying a lambda that prints each key-value pair.
  • The lambda receives two parameters: key and value.
  • We print each key-value pair to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf(1 to "one", 2 to "two", 3 to "three")
    map.forEach { key, value -> println("$key: $value") }
}

Output

1: one
2: two
3: three

2 Print key-value pairs of a map of integers

In this example,

  • We create a map where keys are strings and values are integers.
  • We use the forEach function on the map, applying a lambda that prints each key-value pair.
  • The lambda receives two parameters: key and value.
  • We print each key-value pair to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf("A" to 1, "B" to 2, "C" to 3)
    map.forEach { key, value -> println("$key: $value") }
}

Output

A: 1
B: 2
C: 3

3 Print key-value pairs of a map of strings to integers

In this example,

  • We create a map where keys are strings and values are integers.
  • We use the forEach function on the map, applying a lambda that prints each key-value pair.
  • The lambda receives two parameters: key and value.
  • We print each key-value pair to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
    map.forEach { key, value -> println("$key: $value") }
}

Output

apple: 5
banana: 6
cherry: 7

Summary

In this Kotlin tutorial, we learned about forEach() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.