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.

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:
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.
Map<String, Integer> map = new HashMap<>();
map.merge("cpu", 4, Integer::sum);
System.out.println(map.get("cpu")); // 4Key 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.
map.merge("cpu", 2, Integer::sum);
System.out.println(map.get("cpu")); // 6Remapping function returns null. The entry is removed from the map entirely. This is useful for deleting entries conditionally during an update.
map.merge("cpu", 100, (old, value) -> null);
System.out.println(map.containsKey("cpu")); // falseThe 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:
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:
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:
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.
| Method | Key absent | Key present | Function arguments |
|---|---|---|---|
| put | Inserts value | Replaces value | none |
| merge | Inserts value | Applies function to old and new value | old value, new value |
| compute | Applies function to key with a null value | Applies function to key and current value | key, 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:
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.
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.
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 toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.