Map.forEach()
Runs an action for every pair of a map.
Available since: Java 8
Syntax
default void forEach(BiConsumer<? super K, ? super V> action)Parameters
| Parameter | Type | Description |
|---|---|---|
| action | BiConsumer<? super K, ? super V> | An action that receives the key and the value. |
Examples
Printing pairs with a lambda:
void main() {
Map<String, Integer> ages = new TreeMap<>(Map.of("Anna", 31, "Oleg", 25));
ages.forEach((name, age) -> IO.println(name + " is " + age));
}Output:
Anna is 31
Oleg is 25Notes
The lambda receives two parameters at once — the key and the value, without Map.Entry. It must not change the map itself (add or remove keys). If you need break or a return from the enclosing method, use a regular loop over entrySet().
See also
- Map.entrySet() — Returns all key and value pairs for iteration.
- Iterable — The interface of everything that a for-each loop can iterate over.
- Stream.forEach() — Runs an action for every stream element (a terminal operation).
Related recipes
In the tutorial
- Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.