Java TreeMap forEach() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

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));
CallWhat 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

ParameterDescription
action (BiConsumer<? super K, ? super V>)Code to run for each key/value pair; must not be null.

Return Value

Return ValueDescription
voidNothing; the work happens inside the action.

Compare with Similar Methods

Ways to visit every mapping:

MethodHow it differs
entrySet()A classic loop that can break early.
replaceAll(f)Recomputes every value.
keySet()Visit keys only.
HashMap.forEach()Same method, unordered.

Java Examples

Example 1 — A Sorted Temperature Report

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);
    }
}

How It Works

  1. The action as a value. The lambda is stored in a BiConsumer<String, Integer>; its two parameters receive each city and temperature.
  2. Cities in alphabetical order. forEach walks the tree from the smallest key, so Cairo comes first and Oslo last.
  3. 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]);
    }
}

How It Works

  1. Effectively final holders. csv and total never point to new objects, so the lambda may use them while changing their contents.
  2. 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.
  3. 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);
    }
}

How It Works

  1. 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".
  2. The new key stays. The exception does not roll anything back, so "a2" is part of the map afterwards.
  3. 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.

Next: get()

Read the value stored under a key.

get() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful