In Java, merge(key, value, remappingFunction) stores value if key is missing or mapped to null. Otherwise it calls remappingFunction(oldValue, value) and stores the result.
If the function returns null, the key is removed. The classic use is counting: counts.merge(word, 1, Integer::sum) inserts 1 for a new word and adds 1 for a word already seen.
An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. merge was added in Java 8 as a default method of Map; HashMap overrides it.
Syntax
Pass the key, a non-null value, and a function of (oldValue, value).
The general form when you need the key in the function.
The function receives the old and the new values, not the key. When the key is missing, the function is not called at all.
Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction)
// Default method in Map<K, V>, overridden by HashMap
Parameters
Parameter
Description
key (K)
The key to insert or combine.
value (V)
Stored if the key is missing; otherwise passed as the second argument. Must not be null.
remappingFunction
Combines the old value and value; returning null removes the key. Must not be null.
Return Value
Return Value
Description
V
The new value now stored for key.
null
The function returned null and the key was removed.
Example 1 — Count Words with merge and Integer::sum
The classic one-line word counter.
Java
import java.util.HashMap;
import java.util.Map;
public class HashMapMergeDemo {
public static void main(String[] args) {
String text = "the cat and the hat and the bat";
Map<String, Integer> counts = new HashMap<>();
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts);
System.out.println("the: " + counts.get("the"));
}
}
Output
{the=3, bat=1, and=2, cat=1, hat=1}
the: 3
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
Split into words.text.split(" ") produces eight words, three of them "the" and two "and".
New word. The first time a word appears, there is nothing to combine, so the value 1 is stored as is.
Repeated word. Later, Integer::sum receives the old count and 1 and stores their sum.
Unordered result. The counts print in hash order, so sort them (for example with a TreeMap copy) if the order matters.
Example 2 — Collect Tags per Post
Merge comma-separated tags into one string per post.
Java
import java.util.HashMap;
import java.util.Map;
public class HashMapMergeTags {
public static void main(String[] args) {
String[][] tags = {{"post1", "java"}, {"post2", "css"}, {"post1", "maps"}, {"post1", "beginner"}};
Map<String, String> tagLine = new HashMap<>();
for (String[] t : tags) {
tagLine.merge(t[0], t[1], (oldTags, tag) -> oldTags + ", " + tag);
}
System.out.println("post1: " + tagLine.get("post1"));
System.out.println("post2: " + tagLine.get("post2"));
}
}
Output
post1: java, maps, beginner
post2: css
How It Works
First tag stored directly. post1 has no tags yet, so "java" is stored without calling the lambda.
Join later tags. For "maps", the lambda receives the old string "java" and the new tag and returns "java, maps".
Arguments are values. The two lambda parameters are the old value and the new value; the key itself is not passed.
Single tag. post2 only ever receives "css", so its value is never combined.
Example 3 — Adjust Cart Quantities and Remove at Zero
Subtract from quantities with a reusable BiFunction that returns null at zero, then try a null value.
Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BiFunction;
public class HashMapMergeRemove {
public static void main(String[] args) {
Map<String, Integer> cart = new HashMap<>();
cart.put("apples", 3);
cart.put("pears", 2);
BiFunction<Integer, Integer, Integer> adjust = (qty, change) -> qty + change <= 0 ? null : qty + change;
Integer a = cart.merge("apples", -1, adjust);
Integer p = cart.merge("pears", -2, adjust);
Integer k = cart.merge("kiwis", 4, adjust);
System.out.println("apples -> " + a + ", pears -> " + p + ", kiwis -> " + k);
System.out.println(new TreeMap<>(cart));
try {
cart.merge("plums", null, adjust);
} catch (NullPointerException e) {
System.out.println("merge with a null value -> NullPointerException");
}
}
}
Output
apples -> 2, pears -> null, kiwis -> 4
{apples=2, kiwis=4}
merge with a null value -> NullPointerException
How It Works
Reusable function.adjust is a BiFunction<Integer, Integer, Integer> stored in a variable, so all three calls share the same rule.
Subtract or remove. apples go from 3 to 2; pears reach 0, so adjust returns null and the pears mapping is removed.
Missing key. kiwis are not in the cart, so 4 is stored directly and adjust is never called.
No null values.merge requires a non-null value, so passing null throws NullPointerException before anything happens.
Frequently Asked Questions
Loop over the words and call counts.merge(word, 1, Integer::sum). New words get 1, and repeated words get their count increased by 1.
It stores the given value without calling the function and returns that value.
Return null from the function. If the key exists, its mapping is removed.
No. merge() throws NullPointerException when the value is null.
merge() takes a value and combines it with the old one; its function never sees the key. compute() passes the key and the old value (or null) to the function.