In Java, forEach(action) calls action once for each mapping in a HashMap, passing the key and the value. The action is a BiConsumer<K, V>, usually written as a lambda such as (k, v) -> System.out.println(k + "=" + v).
It visits entries in the same internal order as entrySet(), which is not guaranteed. It is great for printing and collecting, but it has no way to remove the current entry.
An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. forEach(BiConsumer) was added in Java 8 as a default method of Map; HashMap overrides it to walk its table directly.
Syntax
Pass a lambda that takes a key and a value.
Java
Map<String, Integer> temps = new HashMap<>();
temps.put("Oslo", -3);
temps.forEach((city, t) -> System.out.println(city + ": " + t));
Call
What it does
map.forEach((k, v) -> ...)
Runs the lambda for every mapping.
new TreeMap<>(map).forEach(...)
Same, but in sorted key order.
map.keySet().forEach(k -> ...)
Keys only (the Iterable.forEach method).
map.values().forEach(v -> ...)
Values only.
Local variables used inside the lambda must be effectively final. To accumulate a total, use a one-element array, an object field, or a plain for loop over entrySet().
Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public void forEach(BiConsumer<? super K, ? super V> action)
// Default method in Map<K, V>, overridden by HashMap
Parameters
Parameter
Description
action (BiConsumer<? super K, ? super V>)
Code to run for each key and value. Must not be null.
Return Value
Return Value
Description
void
Nothing. Results must be collected by the action itself.
import java.util.HashMap;
import java.util.Map;
public class HashMapForEachDemo {
public static void main(String[] args) {
Map<String, Integer> temps = new HashMap<>();
temps.put("Lima", 18);
temps.put("Oslo", -3);
temps.put("Cairo", 24);
temps.forEach((city, t) -> System.out.println(city + ": " + t + " C"));
}
}
Output
Oslo: -3 C
Lima: 18 C
Cairo: 24 C
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
Two parameters. The lambda (city, t) -> ... matches BiConsumer<String, Integer>: the map passes each key as city and its value as t.
No loop variable. There is no Map.Entry to declare; the map drives the iteration itself.
Negative values print normally. Oslo's -3 is just another Integer value.
Table order. Oslo's hash picks an earlier bucket than the others, so it prints first even though Lima was added first. Lima and Cairo share one bucket, and within it Lima, stored earlier, comes first.
Example 2 — Total Sales and Strong Regions
Accumulate a total in a one-element array and collect regions with sales of at least 100.
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashMapForEachTotal {
public static void main(String[] args) {
Map<String, Integer> sales = new HashMap<>();
sales.put("north", 120);
sales.put("south", 80);
sales.put("east", 150);
sales.put("west", 95);
int[] total = {0};
List<String> strong = new ArrayList<>();
sales.forEach((region, amount) -> {
total[0] += amount;
if (amount >= 100) {
strong.add(region);
}
});
Collections.sort(strong);
System.out.println("total: " + total[0]);
System.out.println("100 or more: " + strong);
}
}
Output
total: 445
100 or more: [east, north]
How It Works
Effectively final. A lambda cannot reassign a local int, so the running total lives in total[0]; the array reference itself never changes.
Block lambda. Curly braces let the action run two statements: add to the total and maybe record the region.
Arithmetic. 120 + 80 + 150 + 95 = 445, and only north and east reach 100.
Sort for stable output. The regions are collected in hash order, so Collections.sort fixes the order before printing.
Example 3 — HashMap Order vs TreeMap Order
Print the keys in the map's own order, then in sorted order through a TreeMap copy, and pass null as the action.
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
One line, many prints.System.out.print keeps the keys on the same line, and the following println() ends it.
Hash order. The HashMap visits zeta, alpha, mid, an order decided by the hash codes, not by the alphabet or by insertion.
Sorted copy.new TreeMap<>(ranks) holds the same mappings sorted by key, and its forEach visits them alphabetically.
No null action. Passing null instead of a lambda throws NullPointerException immediately.
Frequently Asked Questions
Pass a lambda with two parameters: map.forEach((key, value) -> System.out.println(key + "=" + value));
Not a local variable directly; locals used in a lambda must be effectively final. Use a one-element array, a field, or a regular loop.
No. Removing or adding keys causes ConcurrentModificationException. Use entrySet().removeIf(...) or an Iterator instead.
In the internal hash-table order, which is not guaranteed. Use new TreeMap<>(map).forEach(...) for sorted keys.