Java TreeMap replaceAll() Method

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

Definition

In Java, replaceAll(function) replaces the value of every entry in a TreeMap with function.apply(key, oldValue). Entries are visited in ascending key order, and keys are never added, removed, or reordered.

Because range views such as headMap and subMap are maps too, you can call replaceAll on a view to rewrite only part of the map. The changes go straight into the original TreeMap.

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 old value and returns the new value.

Java
TreeMap<String, Integer> salaries = new TreeMap<>();
salaries.replaceAll((name, pay) -> pay * 110 / 100);   // +10% for everyone
salaries.headMap("M").replaceAll((name, pay) -> 0);     // only names before "M"
CallWhat it does
map.replaceAll((k, v) -> newV)Rewrites every value.
map.headMap(k).replaceAll(f)Rewrites only the keys below k.
map.replaceAll((k, v) -> v)Leaves values as they are.

The function receives the key too, so new values can depend on it. Returning null stores null; it does not remove the entry.

Library declarations
Java
// java.util.TreeMap<K, V>
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

// Default method of Map<K, V> since Java 8; TreeMap overrides it

Parameters

ParameterDescription
function (BiFunction<? super K, ? super V, ? extends V>)Computes each new value from the key and the old value. Must not be null.

Return Value

Return ValueDescription
voidNothing; the values are changed in place.

Compare with Similar Methods

Changing values:

MethodHow it differs
replace(k, v)Changes one key's value.
entrySet()Loop with setValue when you need more control.
compute(k, f)Recomputes one key and can add or remove it.
HashMap.replaceAllSame call, but entries are visited in hash order.

Java Examples

Example 1 — Give Every Employee a 10% Raise

Integer arithmetic multiplies first and divides second, so no decimals are needed.

Java
import java.util.TreeMap;

public class TreeMapReplaceAllRaise {
    public static void main(String[] args) {
        TreeMap<String, Integer> salaries = new TreeMap<>();
        salaries.put("Iris", 4200);
        salaries.put("Bram", 3800);
        salaries.put("Noor", 5000);

        salaries.replaceAll((name, pay) -> pay * 110 / 100);
        System.out.println(salaries);
        System.out.println(salaries.size() + " salaries raised by 10%");
    }
}

How It Works

  1. One lambda for all. replaceAll calls the lambda for Bram, Iris, and Noor in that (alphabetical) order and stores each result.
  2. Exact integer math. 3800 * 110 / 100 = 4180, 4200 gives 4620, and 5000 gives 5500; multiplying before dividing avoids losing the 10%.
  3. Keys untouched. The size is still 3 and the names keep their places; only the values were rewritten.

Example 2 — Build Room Labels From Key and Value

The new value combines the room number (key) with its use (old value).

Java
import java.util.TreeMap;

public class TreeMapReplaceAllLabels {
    public static void main(String[] args) {
        TreeMap<Integer, String> rooms = new TreeMap<>();
        rooms.put(102, "lab");
        rooms.put(101, "office");
        rooms.put(201, "studio");

        rooms.replaceAll((number, use) -> "Floor " + number / 100 + " " + use.toUpperCase());
        rooms.forEach((number, label) -> System.out.println(number + " -> " + label));
    }
}

How It Works

  1. Floor from the key. number / 100 is integer division, so 101 and 102 give floor 1 and 201 gives floor 2.
  2. Old value reused. The use is upper-cased and appended, so "lab" becomes "Floor 1 LAB".
  3. Numeric order in the loop. forEach prints 101, 102, 201 because Integer keys sort numerically, whatever order they were added in.

Example 3 — Reset Only the Aisles Before "B"

Call replaceAll on a headMap view to touch just one range of keys.

Java
import java.util.TreeMap;

public class TreeMapReplaceAllRange {
    public static void main(String[] args) {
        TreeMap<String, Integer> aisles = new TreeMap<>();
        aisles.put("A1", 14);
        aisles.put("A2", 9);
        aisles.put("B1", 21);
        aisles.put("C1", 7);

        aisles.headMap("B").replaceAll((code, count) -> 0);
        System.out.println(aisles);
        System.out.println("cleared aisles: " + aisles.headMap("B").keySet());
    }
}

How It Works

  1. The view picks the range. headMap("B") holds the keys that sort before "B": A1 and A2. "B1" is greater than "B", so it is outside.
  2. Writes reach the real map. The view has no storage of its own; setting the counts to 0 changes the entries inside aisles.
  3. The rest is untouched. B1 and C1 keep 21 and 7, and a fresh headMap("B") still lists exactly A1 and A2.

Frequently Asked Questions

In ascending key order, the same order in which the map prints.
No. Returning null stores a null value. Use entrySet().removeIf(...) or values().removeIf(...) to delete entries.
Yes. Call it on a view such as headMap, tailMap, or subMap; only the keys in that range change, and the changes appear in the original map.
The function added or removed keys of the map while it was being walked. Only return new values inside the lambda.
Java 8, as a default method of Map; TreeMap has its own override.

Next: size()

Count the key/value mappings.

size() 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.

11 people found this page helpful