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.
In this example,
forEach
function on the map, applying a lambda that prints each key-value pair.key
and value
.fun main(args: Array<String>) {
val map = mapOf(1 to "one", 2 to "two", 3 to "three")
map.forEach { key, value -> println("$key: $value") }
}
1: one 2: two 3: three
In this example,
forEach
function on the map, applying a lambda that prints each key-value pair.key
and value
.fun main(args: Array<String>) {
val map = mapOf("A" to 1, "B" to 2, "C" to 3)
map.forEach { key, value -> println("$key: $value") }
}
A: 1 B: 2 C: 3
In this example,
forEach
function on the map, applying a lambda that prints each key-value pair.key
and value
.fun main(args: Array<String>) {
val map = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
map.forEach { key, value -> println("$key: $value") }
}
apple: 5 banana: 6 cherry: 7
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.