In Java, computeIfPresent(key, function) does something only when key exists in the TreeMap with a non-null value. It then calls function.apply(key, oldValue) and stores the result.
If the function returns null, the key is removed. For a missing key (or one mapped to null) the function is not called, nothing changes, and the method returns null.
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. TreeMap has its own implementation since Java 15 (earlier versions use the Map default); the behaviour is the same.
Syntax
Pass the key and a lambda of the key and the existing value.
Java
TreeMap<String, Integer> balances = new TreeMap<>();
balances.computeIfPresent("ACC-2", (id, owed) -> owed + 15); // only if ACC-2 exists
Call
What it does
map.computeIfPresent(k, (key, v) -> v + 1)
Updates an existing value.
map.computeIfPresent(k, (key, v) -> v > 1 ? v - 1 : null)
Decrements and removes at the end.
map.computeIfPresent(missing, f)
Returns null; f is not called.
It replaces the pattern "if (map.containsKey(k)) map.put(k, f(map.get(k)));" with one tree search.
Library declarations
Java
// java.util.TreeMap<K, V>
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
// Default method of Map<K, V> since Java 8; TreeMap overrides it since Java 15
Parameters
Parameter
Description
key (K)
The key to update. Not null under natural ordering.
remappingFunction
BiFunction of the key and the existing non-null value. Must not be null.
Return Value
Return Value
Description
V
The new value stored for the key.
null
The key was absent or mapped to null, or the function returned null and the key was removed.