Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java HashMap merge: Syntax and Use Cases

Learn how Java's HashMap.merge combines existing and new values, treats an existing null as absent, and simplifies counting and map-merging logic.

~5 min readJava
#HashMap#Java Collections#Map API#ConcurrentHashMap
Editorial diagram of two key-value cards merging into one combined entry, illustrating the Java HashMap merge operation.

When you need to update a map entry based on its current value, HashMap.merge is a clean choice. It was added in Java 8 as a default method on the Map interface, and HashMap overrides it. It combines a key's existing value with a new value using a remapping function.

What HashMap.merge Does

The method signature is:

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

The method takes three arguments: the key to update, a new value to combine with the existing value, and a BiFunction that receives the old value and the new value and returns the result. The return value is the value now associated with the key, or null if the entry was removed.

The remapping function is invoked only when the key is already associated with a non-null value. If the key is absent or mapped to null, merge inserts the given value without calling the function. The value argument must be non-null, and the remapping function must also be non-null; passing null for either throws NullPointerException.

The Three Paths Through merge

Every call to merge follows one of three paths, assuming a non-null value argument.

Key absent or mapped to null. The map associates the key with the given value. The remapping function is not called.

java
Map<String, Integer> map = new HashMap<>(); map.merge("cpu", 4, Integer::sum); System.out.println(map.get("cpu")); // 4

Key present with a non-null value. The remapping function is called with the old value and the new value. The returned value replaces the existing mapping.

java
map.merge("cpu", 2, Integer::sum); System.out.println(map.get("cpu")); // 6

Remapping function returns null. The entry is removed from the map entirely. This is useful for deleting entries conditionally during an update.

java
map.merge("cpu", 100, (old, value) -> null); System.out.println(map.containsKey("cpu")); // false

The remapping function must not modify the same map during the merge operation. Doing so is not supported and can lead to inconsistent state or a ConcurrentModificationException.

Practical Examples: Counting and Combining

The most common use of merge is counting occurrences. The classic alternative is a get-and-put sequence that needs a getOrDefault check on every iteration:

java
Map<String, Integer> counts = new HashMap<>(); for (String word : words) { counts.put(word, counts.getOrDefault(word, 0) + 1); }

With merge, the same logic becomes a single call:

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

When the key is absent, merge inserts 1. When the key is present, it adds 1 to the existing count. The Integer::sum method reference is a natural fit because the remapping function receives the old count and the new value.

Another common pattern is merging two maps into one:

java
Map<String, Integer> base = new HashMap<>(); Map<String, Integer> overlay = new HashMap<>(); overlay.forEach((key, value) -> base.merge(key, value, Integer::sum));

This accumulates overlay values into base without overwriting existing entries. If a key exists in both maps, the values are summed; if it exists only in overlay, it is inserted unchanged.

merge vs put vs compute

put, merge, and compute are easy to confuse because all three update an entry. The difference is in how the new value is produced and when the function runs.

MethodKey absentKey presentFunction arguments
putInserts valueReplaces valuenone
mergeInserts valueApplies function to old and new valueold value, new value
computeApplies function to key with a null valueApplies function to key and current valuekey, current value (null if absent)

put is the right choice when you simply want to replace the value unconditionally. merge is right when the update depends on the existing value and you want the absent-key case to fall back to a default. compute is useful when you want the function to receive the key as well as the current value. merge is usually clearer when you already have a value to combine.

A concrete example of compute:

java
map.compute("session", (key, value) -> value == null ? 1 : value + 1);

This behaves similarly to merge for counting, but the function receives the key and the existing value. merge is usually clearer when you already have a value to combine.

Null Handling in merge

Nulls interact with merge differently than with put. The value argument passed to merge cannot be null: HashMap.merge throws NullPointerException if the second argument is null. However, an existing mapping with a null value is treated the same as an absent key. In that case, merge inserts the supplied value without calling the remapping function. If the remapping function returns null, the entry is removed.

java
Map<String, Integer> map = new HashMap<>(); map.put("a", null); map.merge("a", 10, Integer::sum); System.out.println(map.get("a")); // 10 // This call throws NullPointerException; null is not allowed as the value argument. map.merge("missing", null, Integer::sum);

This behavior makes merge safe to call without a containsKey check, as long as the value argument is non-null. It cannot be used to insert a null value into a map; use put when you need to store null.

Concurrency and Thread Safety

HashMap itself is not thread-safe, and merge does not change that. Concurrent modification from multiple threads can corrupt the map's internal structure. If you need merge to run atomically across threads, use ConcurrentHashMap, which implements the same merge method with atomic semantics.

java
ConcurrentHashMap<String, Long> counters = new ConcurrentHashMap<>(); counters.merge("requests", 1L, Long::sum);

The merge operation on ConcurrentHashMap is performed atomically, so concurrent calls for the same key do not lose updates. This is the standard way to maintain a shared counter or accumulator in a multithreaded context. The remapping function is still executed under the map's internal lock for that bin, so the function should be short and must not call back into the same map.

Performance Considerations

A practical benefit of merge is that it removes the explicit containsKey or getOrDefault check. For a counting loop, merge also avoids repeating the same update logic in several places.

The main thing to watch is the remapping function itself. It runs for every update to an existing non-null value, so it should be cheap. A function that performs I/O, allocates large objects, or calls into the same map can turn a simple counter into a bottleneck. For a count of Integer values, a simple method reference like Integer::sum is easy to read and does no I/O or map mutation.

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.