Java Reference ยท Collections
Java Map.computeIfAbsent()
Reference for Map.computeIfAbsent(): create and store a value only when a key is missing, group items into lists, memoize results, and avoid recursion traps.
computeIfAbsent(key, mappingFunction) returns the value for key if there is one. If the key is missing (or mapped to null), it calls your function with the key, stores the result and returns it. The function runs only when needed, so it is a lazy, one-step replacement for "check, create, put, return".
Its best-known use is a map of collections: map.computeIfAbsent(key, k -> new ArrayList<>()).add(item) groups items without any if.
Map<String, List<String>> groups = new HashMap<>(); groups.computeIfAbsent("fruit", k -> new ArrayList<>()).add("apple");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
| Name | Description |
|---|---|
key |
The key to look up. |
mappingFunction |
Computes the value from the key. Called at most once, and only if no non-null value is present. |
Returns: the existing value, or the newly computed one; null if the function returned null (then nothing is stored).
Throws: NullPointerException if mappingFunction is null. Any exception thrown by the function propagates and leaves the map unchanged. HashMap throws ConcurrentModificationException if the function modifies the map.
Usage notes
- Since Java 8.
HashMap,TreeMap,LinkedHashMapandConcurrentHashMapoverride it with efficient versions. - Lazy: unlike
getOrDefault(k, new ArrayList<>()), the new object is created only when the key is absent. - Returns the value, not the previous one, which is why you can chain
.add(...)directly. - Never modify the map inside the function.
HashMapdetects this and throwsConcurrentModificationException; this rules out naive recursive memoization such as Fibonacci in a singleHashMap. - Null results store nothing, and a key mapped to
nullis treated as absent. - Atomicity: on
ConcurrentHashMapthe function runs atomically per key, so keep it short and free of locks. The defaultMapimplementation is not atomic. - Compared with
putIfAbsent: that method takes a ready-made value (always built), returns the old value and does not return the new one. - Compared with
Collectors.groupingBy: use the collector for a one-shot grouping of a stream.