In Java, computeIfAbsent(key, function) looks up key. If the key is missing (or mapped to null), it calls function.apply(key), stores the result, and returns it. If the key already has a value, the function is not called and the existing value is returned.
This makes it perfect for "get the list for this key, creating it first if needed", and for caches where computing a value is slow. With a TreeMap the groups or cached items come out sorted by key.
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 function that builds the value from the key.
Java
TreeMap<Integer, List<String>> byGrade = new TreeMap<>();
byGrade.computeIfAbsent(3, g -> new ArrayList<>()).add("Omar");
Call
What it does
map.computeIfAbsent(k, x -> new ArrayList<>()).add(v)
Group values under a key.
map.computeIfAbsent(k, x -> load(x))
Cache: compute only on the first request.
map.computeIfAbsent(k, x -> null)
Stores nothing; returns null.
Since the method returns the value in the map, you can chain .add(...) directly onto it.
Library declarations
Java
// java.util.TreeMap<K, V>
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
// Default method of Map<K, V> since Java 8; TreeMap overrides it since Java 15
Parameters
Parameter
Description
key (K)
The key to look up. Not null under natural ordering.
mappingFunction (Function<? super K, ? extends V>)