Java HashMap merge() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

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).

Java
Map<String, Integer> counts = new HashMap<>();
counts.merge("the", 1, Integer::sum);   // 1 (inserted)
counts.merge("the", 1, Integer::sum);   // 2 (1 + 1)
CallWhat it does
map.merge(k, 1, Integer::sum)Count occurrences.
map.merge(k, s, String::concat)Join strings.
map.merge(k, v, (a, b) -> null)Remove k if it exists; otherwise store v.
map.compute(k, f)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

ParameterDescription
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.
remappingFunctionCombines the old value and value; returning null removes the key. Must not be null.

Return Value

Return ValueDescription
VThe new value now stored for key.
nullThe function returned null and the key was removed.

Compare with Similar Methods

Combining values:

MethodHow it differs
compute(k, f)Function receives the key and old value; handles the missing case itself.
putAll(m)Overwrites instead of combining.
getOrDefault + putThe longer pre-Java 8 counting idiom.
computeIfPresent(k, f)Updates only existing keys.

Java Examples

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"));
    }
}

How It Works

  1. Split into words. text.split(" ") produces eight words, three of them "the" and two "and".
  2. New word. The first time a word appears, there is nothing to combine, so the value 1 is stored as is.
  3. Repeated word. Later, Integer::sum receives the old count and 1 and stores their sum.
  4. 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"));
    }
}

How It Works

  1. First tag stored directly. post1 has no tags yet, so "java" is stored without calling the lambda.
  2. Join later tags. For "maps", the lambda receives the old string "java" and the new tag and returns "java, maps".
  3. Arguments are values. The two lambda parameters are the old value and the new value; the key itself is not passed.
  4. 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");
        }
    }
}

How It Works

  1. Reusable function. adjust is a BiFunction<Integer, Integer, Integer> stored in a variable, so all three calls share the same rule.
  2. Subtract or remove. apples go from 3 to 2; pears reach 0, so adjust returns null and the pears mapping is removed.
  3. Missing key. kiwis are not in the cart, so 4 is stored directly and adjust is never called.
  4. 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.

Next: put()

Add a mapping or overwrite an existing value.

put() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful