Map.computeIfAbsent()
Returns the value for a key, creating it with a function if the key is absent.
Available since: Java 8
Syntax
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | K | The key. |
| mappingFunction | Function<? super K, ? extends V> | Creates a value from the key; called only when the key is absent. |
Return value
VThe current (existing or newly created) value.
Examples
Grouping words by the first letter:
void main() {
Map<Character, List<String>> byLetter = new TreeMap<>();
for (String w : List.of("apple", "bean", "avocado", "beet", "corn")) {
byLetter.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
}
IO.println(byLetter);
}Output:
{a=[apple, avocado], b=[bean, beet], c=[corn]}A simple cache: the function runs once per key:
void main() {
Map<Integer, Long> cache = new HashMap<>();
Function<Integer, Long> slowSquare = n -> {
IO.println("computing " + n);
return (long) n * n;
};
IO.println(cache.computeIfAbsent(12, slowSquare));
IO.println(cache.computeIfAbsent(12, slowSquare));
}Output:
computing 12
144
144Notes
The main use is a map of lists: map.computeIfAbsent(key, k -> new ArrayList<>()).add(value). If the function returns null, no pair is added. The function must not modify the same map. Related methods: computeIfPresent() and compute().
See also
- Map.putIfAbsent() — Stores a value only if the key is not present yet.
- Map.merge() — Adds a value under a key or combines it with the existing one.
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
Related recipes
In the tutorial
- Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.