Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java HashMap compute: In-Place Value Updates

HashMap.compute updates an entry in place with a remapping function. See when to use it, how it differs from merge and computeIfAbsent, and common pitfalls.

~5 min readJava
#Java#HashMap#Map API#Functional Programming
Illustration of a Java HashMap entry being updated in place by a compute remapping function

The compute method on java.util.HashMap lets you update a value in place using a remapping function. When you call map.compute(key, remappingFunction), the function receives the current key and the current value (null if the key is absent) and returns the new value. If the returned value is null, the mapping is removed. This makes compute a compact way to express read-modify-write logic that would otherwise require separate get, null-check, and put calls.

The compute Method Signature and Behavior

The signature is:

java
V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

The remappingFunction is applied to the key and the current value. If the key is not present, the current value is null. The function's return value becomes the new mapping. If the function returns null, the entry is removed (or not added if the key was absent). This behavior is consistent across HashMap and ConcurrentHashMap, though the concurrency guarantees differ.

Basic Usage Example

Suppose you are counting word frequencies. With compute, you can increment the count in one line:

java
Map<String, Integer> counts = new HashMap<>(); String word = "apple"; counts.compute(word, (key, count) -> count == null ? 1 : count + 1);

The lambda receives the existing count, or null if the word has not been seen yet. This avoids the verbose pattern of checking containsKey and then calling put. On a ConcurrentHashMap, it also avoids the race between a separate get and put; a plain HashMap provides no such atomicity guarantee.

When compute Is Better Than get + put

The manual approach looks like this:

java
Integer current = map.get(key); int newValue = (current == null) ? 1 : current + 1; map.put(key, newValue);

This works in a single-threaded environment, but it is not atomic. Between the get and the put, another thread could modify the same key, causing a lost update. compute performs the read and write as a single atomic operation on ConcurrentHashMap. Even on a plain HashMap, it reduces the chance of logic errors by keeping the update logic in one place.

compute vs merge vs computeIfAbsent

These three methods are often confused because they all take a remapping function. The difference lies in when the function is called and what it receives.

MethodFunction receivesFunction called when key absentRemoves entry if function returns null
computekey and current value (or null)YesYes
computeIfAbsentkey onlyYesNo; a null result means no mapping is added
mergecurrent value and given valueNo; absent or null value is set to the given valueYes

computeIfAbsent is useful when you only want to initialize a value if the key is missing. merge is useful when you have an incoming value and want to combine it with the existing one, but it does not call the remapping function when the key is absent (or its value is null); it stores the supplied value directly. compute gives you full control over the entire mapping, including the ability to remove the entry.

Edge Cases and Common Pitfalls

One common pitfall is assuming that compute will never remove an entry. If your remapping function returns null, the entry is removed. This can surprise developers who use compute for decrementing and accidentally return null for a zero value. For example:

java
map.compute(key, (k, v) -> (v == null || v == 0) ? null : v - 1);

This decrements the value but removes the key when it reaches zero. If that is not intended, you must return a non-null value, such as 0.

Another edge case is when the key exists but the value is null. HashMap allows null values, so the remapping function receives null as the current value, which is indistinguishable from an absent key. ConcurrentHashMap does not allow null values, so this ambiguity is specific to implementations such as HashMap. Your function must handle both cases consistently, or check containsKey when you need to distinguish them.

Concurrency Considerations

HashMap is not thread-safe. Using compute on a shared HashMap from multiple threads can still corrupt the map. If you need atomic updates in a concurrent environment, use ConcurrentHashMap. Its compute method is atomic and guarantees that the remapping function is applied exactly once per key. This is particularly valuable for caches or counters that are updated from multiple threads.

The remapping function itself must be fast and must not modify the same map directly. ConcurrentHashMap can block operations on the bin containing the key while the function runs, so a slow function reduces concurrency. The function should be short and simple, and it must not attempt to update any other mappings in the same map.

Performance and Maintainability

From a performance perspective, compute is not a magic bullet. It still requires hashing the key and potentially resizing the map. The main benefit is code clarity and atomicity in concurrent cases. Overusing compute for simple operations that are better expressed with computeIfAbsent, putIfAbsent, or merge can make the code harder to read. Use compute when you need to inspect or modify the current value based on its existing state, and use merge when you have a separate value to combine.

Maintainability improves because the update logic is contained in one lambda, but be careful not to make the lambda too complex. If the remapping function grows beyond a few lines, extract it into a named method for readability.

A Practical Example: Refreshing a Cache From Newer Data

Suppose you have a simple cache that stores a timestamp and a value. You want to update the cache only when the incoming value has a newer timestamp than the stored one. Assume newEntry is already defined in the surrounding code as the CacheEntry you want to store if it is newer, and CacheEntry has a timestamp() method:

java
Map<String, CacheEntry> cache = new ConcurrentHashMap<>(); cache.compute(key, (k, entry) -> { if (entry == null || newEntry.timestamp() > entry.timestamp()) { return newEntry; } return entry; });

If the key is absent, the lambda receives null and stores newEntry. If the existing entry has an older timestamp, it is replaced. Otherwise, the existing entry is kept. The entire check-and-set operation is atomic on a ConcurrentHashMap, preventing lost updates when multiple threads write the same key simultaneously.

This pattern is common in caches and session stores where you need to avoid overwriting newer data with stale data. Without compute, you would need to synchronize externally or risk race conditions.

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.