In Java, replace(key, value) sets a new value for keyonly if the key is already in the TreeMap, and returns the old value. If the key is missing, nothing happens and it returns null. It never inserts.
The three-argument form replace(key, oldValue, newValue) changes the value only when the current value equals oldValue, and returns true or false. Both forms find the key with the map's ordering, so a comparator-equal key is enough.
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
Two overloads: plain replace and conditional replace.
Java
TreeMap<String, Integer> menu = new TreeMap<>();
menu.put("latte", 4);
Integer old = menu.replace("latte", 6); // 4
boolean ok = menu.replace("latte", 6, 7); // true: was 6, now 7
Call
What it does
map.replace(k, v)
Replaces the value if k exists; returns the old value or null.
map.replace(k, oldV, newV)
Replaces only when the current value equals oldV.
map.replace(missing, v)
Does nothing; returns null.
replace changes values only, never the structure of the tree, so it does not disturb an iteration that is running over the map.
Library declarations
Java
// java.util.TreeMap<K, V>
public V replace(K key, V value)
public boolean replace(K key, V oldValue, V newValue)
// Default methods of Map<K, V> since Java 8; TreeMap overrides both
Parameters
Parameter
Description
key (K)
The key whose value should change.
value / newValue (V)
The new value. May be null.
oldValue (V)
Three-argument form only: the value the key must currently have (compared with equals).
Return Value
Return Value
Description
V (two arguments)
The previous value, or null if the key was absent (or mapped to null).