In Java, computeIfAbsent(key, mappingFunction) looks up key. If the key already has a non-null value, that value is returned and the function is not called. Otherwise the function computes a value from the key, which is stored and returned.
Because it returns the value that is now in the map, it is ideal for "get or create": map.computeIfAbsent(k, x -> new ArrayList<>()).add(item) groups items into lists in one line.
An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. computeIfAbsent was added in Java 8 as a default method of Map; HashMap overrides it.
Syntax
Pass the key and a function that creates the value from the key.
Java
Map<Character, List<String>> byLetter = new HashMap<>();
byLetter.computeIfAbsent('a', k -> new ArrayList<>()).add("apple");
byLetter.computeIfAbsent('a', k -> new ArrayList<>()).add("avocado");
// {a=[apple, avocado]}
Call
What it does
map.computeIfAbsent(k, x -> new ArrayList<>()).add(v)
Group values under a key.
map.computeIfAbsent(n, x -> slow(x))
Cache a costly result.
map.putIfAbsent(k, v)
Eager version: v is built even if unused.
If the function returns null, nothing is stored and the method returns null. It never removes an existing mapping.
Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction)
// Default method in Map<K, V>, overridden by HashMap
Parameters
Parameter
Description
key (K)
The key to look up or fill.
mappingFunction (Function<? super K, ? extends V>)
Called with the key only when a value is needed. Must not be null.
Return Value
Return Value
Description
V
The existing value, or the newly computed and stored value.
Build a Map<Character, List<String>> without checking whether each list exists.
Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashMapComputeIfAbsentGroup {
public static void main(String[] args) {
String[] words = {"apple", "bean", "avocado", "cherry", "banana", "corn"};
Map<Character, List<String>> byLetter = new HashMap<>();
for (String w : words) {
byLetter.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
}
System.out.println(byLetter);
System.out.println("b words: " + byLetter.get('b').size());
}
}
Output
{a=[apple, avocado], b=[bean, banana], c=[cherry, corn]}
b words: 2
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
Character keys.w.charAt(0) returns a char, which is autoboxed to a Character key.
Create once. The first word for each letter finds no list, so the lambda creates an empty ArrayList and stores it.
Add to the returned list.computeIfAbsent returns the list now in the map, new or existing, so .add(w) always lands in the right group.
Letter order here. A Character hashes to its own code, so a, b, and c fill neighboring buckets and print alphabetically, by luck.
Example 2 — Cache Slow Lookups
Load each price only once; repeated requests are answered from the map.
Method reference.HashMapComputeIfAbsentCache::loadPrice acts as a Function<String, Integer>: a fake slow lookup that counts its calls.
Miss, then hit. The first "tea" is not cached, so loadPrice runs; the next two "tea" requests return the stored 30 without calling it.
Price rule. The fake price is the name length times 10: tea is 30, and cake and soup are both 40.
Savings. Six requests needed only three loads, one per distinct item.
Example 3 — null Values Get Filled; null Results Store Nothing
A key mapped to null, a key with a value, and a function that returns null.
Java
import java.util.HashMap;
import java.util.Map;
public class HashMapComputeIfAbsentNull {
public static void main(String[] args) {
Map<String, String> nick = new HashMap<>();
nick.put("Robert", null);
nick.put("Catherine", "Cat");
String a = nick.computeIfAbsent("Robert", k -> "Bob");
String b = nick.computeIfAbsent("Catherine", k -> "Kate");
String c = nick.computeIfAbsent("Xavier", k -> null);
System.out.println("Robert -> " + a);
System.out.println("Catherine -> " + b);
System.out.println("Xavier -> " + c + ", stored? " + nick.containsKey("Xavier"));
System.out.println("size " + nick.size());
}
}
Output
Robert -> Bob
Catherine -> Cat
Xavier -> null, stored? false
size 2
How It Works
null counts as absent. Robert is a key, but his value is null, so the function runs and "Bob" replaces the null.
Existing value wins. Catherine already has "Cat", so the "Kate" lambda is never called and "Cat" is returned.
null result. For Xavier the function returns null, so no mapping is created and the method returns null.
Size check. Only Robert and Catherine are keys, so the size stays at 2.
Frequently Asked Questions
The value now associated with the key: the existing value if there was one, otherwise the newly computed value (or null if the function returned null).
Use map.computeIfAbsent(key, k -> new ArrayList<>()).add(value). The list is created the first time a key is seen.
No, unless the key is mapped to null. An existing non-null value is returned without calling the function.
computeIfAbsent() creates the value lazily and returns the current value. putIfAbsent() needs the value up front and returns the previous value (or null).
Not on the same HashMap: the recursive calls modify the map during the outer call. Since Java 9 HashMap throws ConcurrentModificationException. Use get and put instead.