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"
Call
What 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
Parameter
Description
function (BiFunction<? super K, ? super V, ? extends V>)
Computes each new value from the key and the old value. Must not be null.