Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java HashMap computeIfPresent: Updating Values In Place

Learn how Java's HashMap computeIfPresent updates existing values, handles null values, and compares with merge and putIfAbsent.

~5 min readJava
#HashMap#Java Collections#computeIfPresent#Map API
A diagram showing a HashMap entry being updated in place by the computeIfPresent remapping function.

computeIfPresent is a default method on java.util.Map that updates the value for a key only when that key already maps to a non-null value. It was added to the Map interface in Java 8, along with compute, computeIfAbsent, and merge. For a HashMap, it offers a compact way to transform an existing value without first checking whether the key exists.

java
Map<String, Integer> scores = new HashMap<>(); scores.put("alice", 10); scores.computeIfPresent("alice", (key, value) -> value + 5); System.out.println(scores.get("alice")); // 15

The remapping function receives the key and the current value, and returns the new value. If the key is absent, or if the current value is null, the function is not invoked and the map is unchanged.

How computeIfPresent Behaves

The method signature is:

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

The method checks two conditions before calling the function:

  • the key must be present in the map
  • the value associated with the key must be non-null

If both hold, the remapping function is applied. The result of the function determines the next state of the mapping. If the function returns a non-null value, that value replaces the old one. If it returns null, the key is removed from the map entirely.

This behavior makes computeIfPresent useful for both updating and conditionally deleting an entry in a single call.

Return Values and Null Handling

The return value of computeIfPresent is the new value associated with the key after the operation, or null if no update happened. That means a null return is ambiguous: it can mean the key was absent, the old value was null, or the remapping function returned null and removed the entry.

Consider a map that contains a key with a null value:

java
Map<String, Integer> map = new HashMap<>(); map.put("key", null); map.computeIfPresent("key", (k, v) -> 42); System.out.println(map.containsKey("key")); // true System.out.println(map.get("key")); // null

Because the existing value is null, the function never runs. This is a common source of confusion: computeIfPresent does not treat a null value as a present mapping. If you need to handle null values as valid data, this method is not the right choice.

Practical Use Cases

The most common use case is updating a counter or aggregating a value only when an entry already exists.

java
Map<String, Integer> wordCount = new HashMap<>(); wordCount.put("error", 3); // Increment only if the word has been seen before wordCount.computeIfPresent("error", (k, count) -> count + 1);

Another typical pattern is transforming a stored object, such as updating a field on a value object:

java
Map<String, User> users = new HashMap<>(); users.put("u1", new User("alice", false)); users.computeIfPresent("u1", (id, user) -> { user.setActive(true); return user; });

Here the returned object controls whether the entry remains in the map: returning the same object keeps the entry mapped, while returning null would remove it. This pattern updates the existing object, so it is not thread-safe if multiple threads access the same User instance.

computeIfPresent vs. merge and putIfAbsent

The Map interface offers several methods that look similar but differ in how they handle missing keys and null values.

MethodKey absentKey present, value non-nullKey present, value null
computeIfPresentno effectapplies functionno effect
computeIfAbsentapplies functionno effectapplies function
mergeinserts given valueapplies function with existing valueinserts given value
putIfAbsentinserts given valueno effectinserts given value

merge is the closest alternative. It takes a value and a remapping function, and it handles the absent-key case by inserting the provided value directly:

java
map.merge("error", 1, (oldValue, newValue) -> oldValue + newValue);

This is often a better fit for counters, because the first occurrence inserts 1 and subsequent occurrences combine the values. computeIfPresent requires the key to already exist, so you would need a separate put call for the initial value.

Concurrency Considerations

For a HashMap, computeIfPresent performs a lookup and, when the key maps to a non-null value, invokes the remapping function. HashMap is not thread-safe and does not use bin locks; concurrent modification by another thread can lead to inconsistent map state. If atomic updates are required, use ConcurrentHashMap or synchronize access to the map externally.

ConcurrentHashMap.computeIfPresent is different: it may hold a bin lock while the remapping function runs, so other threads can be blocked during the computation. The remapping function should be short and simple, must not attempt to update any other mapping of the same map, and should not perform blocking work. Violating these constraints can cause other threads to stall or lead to deadlock.

Common Mistakes and Edge Cases

One frequent mistake is modifying the map from inside the remapping function. For ConcurrentHashMap, the computation must not attempt to update any other mapping of the same map. For HashMap, doing so is outside the method's safe contract and can produce unpredictable results; if the map is also being iterated, structural modification can cause a ConcurrentModificationException.

Another mistake is expecting computeIfPresent to insert a default value when the key is missing. It does not. If the goal is "insert if absent, otherwise update", use compute or merge.

A third edge case is the value parameter inside the lambda. The method only invokes the remapping function for existing non-null values, so the value can be treated as non-null inside the function. Returning null removes the entry, which is a valid way to delete a key conditionally:

java
map.computeIfPresent("temp", (k, v) -> v.isExpired() ? null : v);

This removes the entry only when the existing value satisfies the condition.

When a Different Method Fits Better

computeIfPresent is the right tool when you want to transform an existing value and you know the key should already be present. If the key might be absent and you want to insert a default, computeIfAbsent or merge is clearer. If you want to set a value regardless of whether the key exists, put is simpler; if you want to update only existing entries without a remapping function, replace is a simpler choice.

A good rule of thumb: use computeIfPresent when the remapping logic is non-trivial and should run only for existing entries. For simple unconditional updates, put is more readable. For counters where the first occurrence should initialize the value, merge expresses the intent more directly.

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.