In Java, replace(key, value) sets a new value for keyonly if the key is already in the map, and returns the old value. For a missing key it does nothing and returns null; unlike put, it never adds a mapping.
The overload replace(key, oldValue, newValue) changes the value only if the key is currently mapped to oldValue (compared with equals) and returns true or false. It works like a compare-and-set.
An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. Both replace overloads were added in Java 8 as default methods of Map; HashMap overrides them.
Syntax
Two overloads: unconditional, and conditional on the current value.
Java
Map<String, Integer> prices = new HashMap<>();
prices.put("apple", 40);
Integer old = prices.replace("apple", 45); // 40
boolean ok = prices.replace("apple", 45, 50); // true
Integer none = prices.replace("kiwi", 30); // null, not added
Call
What it does
map.replace(k, v)
Replaces if k exists; returns the old value or null.
map.replace(k, old, v)
Replaces only if k maps to old; returns a boolean.
map.put(k, v)
Replaces or adds.
map.replaceAll(f)
Replaces every value with a function.
For the one-argument check, a key mapped to null still counts as present, so its null is replaced.
Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V replace(K key, V value)
public boolean replace(K key, V oldValue, V newValue)
// Default methods in Map<K, V>, overridden by HashMap
Parameters
Parameter
Description
key (K)
The key whose value should change.
value / newValue (V)
The new value. May be null in a HashMap.
oldValue (V)
Three-argument form only: the value the key must currently have.
Return Value
Return Value
Description
V (two arguments)
The previous value, or null if the key was missing (or mapped to null).