Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java HashMap computeIfAbsent: Syntax and Use Cases

Learn how HashMap.computeIfAbsent works: its syntax and behavior, and when to choose it over putIfAbsent or compute for building maps.

~6 min readJava
#HashMap#Java Collections#Map API#Functional Programming
Professional illustration of a Java HashMap using computeIfAbsent to insert a new list value when a key is absent

Java's HashMap.computeIfAbsent method solves a recurring problem: checking whether a key exists in a map, and if it does not, creating and storing a value for it. As a method on the Map interface, its signature is:

java
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

The naive approach requires a conditional check followed by a put call:

java
Map<String, List<String>> groups = new HashMap<>(); List<String> group = groups.get("developers"); if (group == null) { group = new ArrayList<>(); groups.put("developers", group); } group.add("alice");

This pattern is verbose and easy to get wrong. The computeIfAbsent method, added to the Map interface in Java 8, collapses the check-and-put into a single call:

java
Map<String, List<String>> groups = new HashMap<>(); groups.computeIfAbsent("developers", k -> new ArrayList<>()) .add("alice");

If the key "developers" is not present, the lambda runs, the new ArrayList is stored under that key, and the method returns it. If the key is already present, the lambda does not run and the existing value is returned. Either way, the returned list receives "alice".

How the Method Behaves

computeIfAbsent follows a specific set of rules:

  • If the key is not in the map, the mapping function is invoked with the key as its argument.
  • If the mapping function returns a non-null value, that value is stored under the key and returned.
  • If the mapping function returns null, no entry is recorded and null is returned.
  • If the key is already mapped to a non-null value, the mapping function is not invoked and the existing value is returned.
  • If the key is mapped to null (which is possible in a HashMap), it is treated as absent, and the mapping function runs.

This last point matters. A HashMap allows null values, so a key can exist in the map with a null value. computeIfAbsent treats that as if the key were absent and will overwrite the null with the computed value.

A Practical Example: Building a Grouping Map

The most common use of computeIfAbsent is building a map of collections, such as grouping items by a category:

java
Map<String, List<Order>> ordersByCustomer = new HashMap<>(); for (Order order : orders) { ordersByCustomer.computeIfAbsent(order.customerId(), id -> new ArrayList<>()) .add(order); }

Without computeIfAbsent, this loop would need an explicit existence check and a separate put call for every new customer ID. The method also keeps the code free of the temporary local variable that the manual version requires.

The same pattern works with Set:

java
Map<String, Set<String>> permissionsByRole = new HashMap<>(); permissionsByRole.computeIfAbsent(role, r -> new HashSet<>()) .add(permission);

What Happens When the Mapping Function Returns Null

The mapping function is allowed to return null. When it does, no mapping is recorded. This is useful when you want to conditionally create an entry:

java
Map<String, Integer> scores = new HashMap<>(); Integer score = scores.computeIfAbsent("player1", k -> { if (isValidPlayer(k)) { return 100; } return null; });

If isValidPlayer returns false, the key "player1" is not added to the map and score is null. This behavior makes computeIfAbsent useful for conditional caching where some keys should not produce a cached value.

Difference Between computeIfAbsent and putIfAbsent

putIfAbsent is often confused with computeIfAbsent, but they behave differently in important ways:

AspectputIfAbsentcomputeIfAbsent
Value sourceValue is passed directlyValue is computed by a function
Computation costNo function runs; the value is already builtFunction runs only when the key has no non-null mapping
Null handlingIf the key is absent or mapped to null, stores the passed value, even if that value is nullIf the key is absent or mapped to null, computes a replacement and stores it only when the result is non-null
Return valueExisting value or the passed valueExisting value or the computed value

putIfAbsent(key, value) will store the value if the key is absent. But if you pass null as the value, it stores null. computeIfAbsent with a function that returns null does not store anything. This distinction matters when null is not a valid value for your map.

Performance Considerations

The mapping function runs only when the key is absent or mapped to null. This is the main performance advantage over always constructing a value before checking the map when value construction is expensive.

Consider a cache that builds a complex object:

java
Map<String, CompiledPattern> patternCache = new HashMap<>(); CompiledPattern pattern = patternCache.computeIfAbsent( regex, k -> new CompiledPattern(Pattern.compile(k)) );

The Pattern.compile call happens only on the first lookup for each regex string. Subsequent lookups return the cached object without invoking the lambda.

The manual equivalent works, but it needs an explicit get, a null check, and a put:

java
CompiledPattern pattern = patternCache.get(regex); if (pattern == null) { pattern = new CompiledPattern(Pattern.compile(regex)); patternCache.put(regex, pattern); }

That said, the lambda itself is not free. If the mapping function captures state, evaluating it can allocate an object. Even for non-capturing lambdas, the JVM is not required to reuse the same instance, so a hot loop may create unnecessary objects. If allocation matters, storing the function in a Function variable once and passing it avoids repeated lambda creation:

java
Function<String, List<String>> newList = k -> new ArrayList<>(); for (String key : keys) { map.computeIfAbsent(key, newList); }

The pre-built function still creates a new ArrayList for each absent key; the main saving is the function object, not the computed values. For many use cases, per-call lambda allocation is negligible.

Concurrency and Thread Safety

HashMap is not thread-safe, and computeIfAbsent on a plain HashMap provides no atomicity guarantee. If two threads call computeIfAbsent with the same absent key on the same HashMap, both may compute a value, and one will overwrite the other. The mapping function may also run more than once.

ConcurrentHashMap overrides computeIfAbsent with an atomic implementation. For a ConcurrentHashMap, the mapping function is guaranteed to run at most once per key under concurrent access, and the resulting value is published safely to other threads.

There is an important caveat with ConcurrentHashMap: the mapping function must not attempt to update the same map. If it does, the behavior is unspecified and may result in an exception or deadlock. On a plain HashMap, modifying the map from the mapping function is also unsafe and can produce unpredictable results, though the failure mode may differ.

Common Mistakes and Edge Cases

One mistake is using computeIfAbsent when the value is cheap to construct and the key is frequently present. In that situation, the lambda allocation and the method dispatch overhead are unnecessary. A simple get with a fallback may be clearer.

Another edge case is the mapping function modifying the map. The Map interface documentation states that the mapping function should not modify the map during computation. For a HashMap, doing so can produce unpredictable results.

Recursive computation is also a risk. If the mapping function calls computeIfAbsent on the same map with the same key, the behavior depends on the map implementation and can cause a StackOverflowError or ConcurrentModificationException.

Finally, remember that computeIfAbsent returns the existing value when the key is present. If you need to update an existing value based on the current value, use compute or merge instead. computeIfAbsent is specifically for the absent case.

When to Choose an Alternative

computeIfAbsent is the right tool when you need to fetch or create a value for a key in a single operation. It is not the right tool for every map update.

Use put when you always want to overwrite the existing value.

Use putIfAbsent when you already have the value and simply want to avoid overwriting an existing one.

Use compute when the new value depends on the current value, including the case where the current value is null.

Use merge when you need to combine the existing value with a new value, such as summing counts:

java
Map<String, Integer> counts = new HashMap<>(); for (String word : words) { counts.merge(word, 1, Integer::sum); }

The choice comes down to whether the value is precomputed, conditionally computed, or derived from the existing mapping. computeIfAbsent covers the conditional-computation case and keeps the check-and-store operation in one call; cross-thread atomicity still requires ConcurrentHashMap.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.