Java Reference ยท Collections
Java Map.merge()
Reference for Map.merge(): insert a value or combine it with the existing one in a single call, with counters, concatenation, removal on null and pitfalls.
merge(key, value, remappingFunction) combines a new value with whatever is already stored. If the key is absent (or mapped to null), the new value is stored as is. Otherwise your function receives the old value and the new one, and its result replaces the old value. If the function returns null, the entry is removed.
This makes merge the compact way to count, sum, concatenate, or keep a maximum: a single call replaces "get, check, compute, put".
counts.merge(word, 1, Integer::sum);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
| Name | Description |
|---|---|
key |
The key to update. |
value |
The value to store if the key has no value; otherwise the second argument of the function. Must not be null. |
remappingFunction |
Called as f(oldValue, value) when an old value exists. Return null to remove the entry. |
Returns: the new value associated with the key, or null if the entry was removed.
Throws: NullPointerException if value or the function is null (or the map forbids null keys). Exceptions from the function propagate and leave the map unchanged.
Usage notes
- Since Java 8.
HashMap,TreeMapandConcurrentHashMapprovide efficient versions;ConcurrentHashMap.mergeis atomic for the key, which makes it a good thread-safe counter. - Argument order matters for non-commutative functions: the old value is first, the new value second.
- Function receives non-null values only. It is never called with
nullas the old value. - Do not modify the map inside the function;
HashMapmay throwConcurrentModificationException. - Boxed arithmetic:
Integer::sumunboxes and reboxes. For hot loops with huge counts considerLongAddervalues or arrays. - Compared with
compute(): usecomputewhen the new value depends on the key or when absence needs different logic; usemergewhen you have a ready value to fold in. - Common reducers:
Integer::sum,Math::max,String::concat,(a, b) -> a, to keep the first value. Collectors.toMap(k, v, merge)uses the same idea to resolve duplicate keys in streams.