Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Map.merge(): combine values for one key

Use `Map.merge()` to store an initial value, combine it with an existing value, or remove the entry when the combining function returns `null`.

Version: Java SE 21

Syntax

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

map.merge(key, value, (oldValue, incomingValue) -> combinedValue)

Map.merge and Map.merge() refer to the same default method on the java.util.Map interface, available since Java 8. The parentheses in the name do not mean there is a zero-argument version: call it on a map instance with a key, an incoming value, and a combining function (BiFunction).

If the key is absent or mapped to null, the method stores and returns the incoming value without calling the function. Otherwise, the function receives the old value first and the incoming value second — not the key. A non-null result replaces the old value and is returned. A null result removes the entire entry, and the method returns null.

Neither the incoming value nor the function itself can be null. If the map supports merge, passing null for either argument causes a NullPointerException. A null key is allowed only if the map supports it. On an unmodifiable map created by Map.of(), calling merge always throws UnsupportedOperationException, even if the incoming value or the function is null.

If the function throws an unchecked exception, merge propagates it and leaves the existing entry unchanged. The function should not modify the same map while computing the result. The default implementation guarantees neither synchronization nor atomicity; check the documentation for the implementation you use.

For counting, use Integer::sum: the first entry starts at 1, and later occurrences of that key increment the count. TOTAL is an ordinary key that the example updates with a separate call; it does not change automatically when another entry is removed.

Examples

import java.util.HashMap;
import java.util.Map;

public class MergeDemo {
    public static void main(String[] args) {
        Map<String, Integer> counts = new HashMap<>();
        counts.put("apples", null);

        for (String item : new String[] {"apples", "pears", "apples"}) {
            counts.merge(item, 1, Integer::sum);
            counts.merge("TOTAL", 1, Integer::sum);
        }

        System.out.println("apples=" + counts.get("apples"));
        System.out.println("pears=" + counts.get("pears"));
        System.out.println("TOTAL=" + counts.get("TOTAL"));

        Integer result = counts.merge("pears", 1, (oldValue, incomingValue) -> null);
        System.out.println("merge result=" + result);
        System.out.println("contains pears=" + counts.containsKey("pears"));
    }
}

Result

apples=2
pears=1
TOTAL=3
merge result=null
contains pears=false

`HashMap` lets `apples` start mapped to `null`, while `pears` starts absent. Both counts start at `1` without calling `Integer::sum`. At the end, the function that returns `null` removes `pears`; `containsKey` confirms the removal.

Related lessons

  • Java · Lesson 56 · Basic · Version: 2
  • Java · Lesson 39 · Intermediate · Version: 2

Sources