Java 25 (LTS) reference · Map and HashMap Methods
Java Map computeIfAbsent() Method
Return the value for a key, creating and storing it with a function first if the key is missing. Ideal for grouping.
Java 25 (LTS) Since Java 8
Syntax
map.computeIfAbsent(key, mappingFunction)
Parameters
| Parameter | Description |
|---|---|
keyK |
The key. |
mappingFunctionFunction |
Creates the value for a missing key. |
Return value
The existing or new value.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, List<String>> byLength = new TreeMap<>();
for (String w : List.of("tea", "mug", "kettle", "cup")) {
byLength.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
}
System.out.println(byLength);
}
}
Output
{3=[tea, mug, cup], 6=[kettle]}Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> cache = new HashMap<>();
int[] calls = {0};
for (String s : List.of("ab", "ab", "abc")) cache.computeIfAbsent(s, k -> { calls[0]++; return k.length(); });
System.out.println(new TreeMap<>(cache) + ", computed " + calls[0] + " times");
}
}
Output
{ab=2, abc=3}, computed 2 timesRun this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
map.putIfAbsent()· Add a key-value pair only if the key is missing (or mapped to null). Returns the existing value otherwise.stream.collect(Collectors.groupingBy())· Group elements into a Map by a key function, optionally counting or summing each group.- Java HashMap · tutorial