In Java, forEach(action) calls action.accept(key, value) for every mapping of a TreeMap, in ascending key order. The action is a BiConsumer<K, V>, usually written as a lambda such as (k, v) -> ....
It was added in Java 8 as a default method of Map, and TreeMap overrides it to walk the tree directly. It is a compact alternative to looping over entrySet().
An instance method of java.util.TreeMap, added in Java 8 as part of the Map interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.
Syntax
Pass a lambda that takes the key and the value.
Java
TreeMap<String, Integer> temps = new TreeMap<>();
temps.forEach((city, t) -> System.out.println(city + ": " + t));
Call
What it does
map.forEach((k, v) -> ...)
Runs the lambda once per mapping, in key order.
map.entrySet().forEach(e -> ...)
Same visit, with an entry object.
map.replaceAll((k, v) -> ...)
Use this to change every value.
Local variables used inside the lambda must be effectively final, so counters are usually kept in a one-element array, an AtomicInteger, or a StringBuilder.
Library declarations
Java
// java.util.TreeMap<K, V>
public void forEach(BiConsumer<? super K, ? super V> action)
// Declared in Map<K, V> (Java 8)
Parameters
Parameter
Description
action (BiConsumer<? super K, ? super V>)
Code to run for each key/value pair; must not be null.
A BiConsumer variable holds the printing logic and is passed to forEach.
Java
import java.util.TreeMap;
import java.util.function.BiConsumer;
public class TreeMapForEachReport {
public static void main(String[] args) {
TreeMap<String, Integer> temps = new TreeMap<>();
temps.put("Oslo", -3);
temps.put("Cairo", 24);
temps.put("Lima", 18);
BiConsumer<String, Integer> line = (city, t) -> System.out.println(city + ": " + t + " C");
temps.forEach(line);
}
}
Output
Cairo: 24 C
Lima: 18 C
Oslo: -3 C
How It Works
The action as a value. The lambda is stored in a BiConsumer<String, Integer>; its two parameters receive each city and temperature.
Cities in alphabetical order.forEach walks the tree from the smallest key, so Cairo comes first and Oslo last.
Negative numbers print as usual. Oslo's value -3 is concatenated like any other Integer.
Example 2 — Build a Summary Inside forEach()
A StringBuilder and a one-element array collect results across calls.
Java
import java.util.TreeMap;
public class TreeMapForEachCollect {
public static void main(String[] args) {
TreeMap<String, Integer> hours = new TreeMap<>();
hours.put("Wed", 7);
hours.put("Mon", 8);
hours.put("Tue", 6);
StringBuilder csv = new StringBuilder();
int[] total = {0};
hours.forEach((day, h) -> {
csv.append(day).append('=').append(h).append(';');
total[0] += h;
});
System.out.println("csv: " + csv);
System.out.println("total: " + total[0]);
}
}
Output
csv: Mon=8;Tue=6;Wed=7;
total: 21
How It Works
Effectively final holders.csv and total never point to new objects, so the lambda may use them while changing their contents.
Lucky alphabetical order. Mon, Tue, Wed happen to sort alphabetically in calendar order; Thu or Fri would not, so real code would use day numbers as keys.
Sum across calls.total[0] collects 8 + 6 + 7 = 21 as the action runs three times.
Example 3 — Adding a Key Inside forEach() Throws
The first call adds a key and the loop stops; updating existing values afterwards is fine.
Java
import java.util.ConcurrentModificationException;
import java.util.TreeMap;
public class TreeMapForEachCme {
public static void main(String[] args) {
TreeMap<String, Integer> m = new TreeMap<>();
m.put("a", 1);
m.put("b", 2);
m.put("c", 3);
try {
m.forEach((k, v) -> {
System.out.println("visiting " + k);
if (k.equals("a")) {
m.put("a2", 0);
}
});
} catch (ConcurrentModificationException e) {
System.out.println("forEach: " + e.getClass().getSimpleName());
}
m.forEach((k, v) -> m.put(k, v * 10));
System.out.println("map: " + m);
}
}
Output
visiting a
forEach: ConcurrentModificationException
map: {a=10, a2=0, b=20, c=30}
How It Works
Checked after every call. The action for "a" prints its line and adds "a2"; when it returns, forEach notices the structural change and throws before visiting "b".
The new key stays. The exception does not roll anything back, so "a2" is part of the map afterwards.
Value updates are allowed.put on keys that already exist only replaces values, so the second forEach multiplies every value by 10 without an exception.
Frequently Asked Questions
In ascending key order, the same order as entrySet() iteration.
In Java 8, as a default method of Map that TreeMap overrides.
Replacing values of existing keys is fine. Adding or removing keys causes ConcurrentModificationException.
You cannot; it visits every entry. Use a for loop over entrySet() with break, or a stream with a short-circuiting operation.
BiConsumer<? super K, ? super V>, a function that takes the key and the value and returns nothing.