CKTIS / Java
Map.forEach: act on each key–value pair
`Map.forEach` visits entries directly on a map. It passes two arguments to a `BiConsumer`: the key first, then the associated value.
Version: Java SE 21
Syntax
default void forEach(BiConsumer<? super K, ? super V> action)Map.forEach is a default method on java.util.Map<K, V>, available since Java 8. It takes a BiConsumer<? super K, ? super V> and calls accept(key, value) for each entry. You can write the action as a lambda, (key, value) -> .... Neither the action nor the method returns a result (void).
Map.forEach works directly on the map. In contrast, Stream.forEach is a terminal stream operation that takes a Consumer with one argument per element. In map.entrySet().stream().forEach(...), that argument is a Map.Entry object, not two separate arguments.
If the map has a specified iteration order, actions follow the iteration order of entrySet() unless the implementation specifies otherwise. Do not assume every map preserves insertion order; HashMap does not guarantee it.
If the action throws an exception, traversal stops and the exception propagates to the caller. A null action causes NullPointerException. Avoid adding or removing entries inside the action: a removal detected during traversal can cause ConcurrentModificationException. The default implementation guarantees neither synchronization nor atomicity.
Examples
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new LinkedHashMap<>();
stock.put("pear", 3);
stock.put("apple", 5);
stock.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
Result
pear: 3 apple: 5
The lambda receives a `String` key and an `Integer` value. `new LinkedHashMap<>()` preserves insertion order, so `pear` appears before `apple`.
Related lessons
- Java · Lesson 42 · Intermediate · Version: 2