Java SE API

Map.merge

Insert for an absent or null mapping; otherwise combine values. A null callback result removes the mapping. Optional mutation; default method makes no atomicity guarantee.

Formal Syntax & Structure

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

Parameters & Attributes

NameTypeDescription
keyKTarget key.
valueVNon-null incoming value.
remappingFunctionBiFunction<? super V, ? super V, ? extends V>Combines old and incoming values.

Return Value

V

New value, or null if removed.

Working Example

Example Snippetjava
import java.util.*;public class Main {
    public static void main(String[] args) {        Map<String, Integer> counts = new TreeMap<>();        for (String word : List.of("pear", "apple", "pear", "plum")) {            counts.merge(word, 1, (oldValue, added) -> oldValue + added);        }        for (Map.Entry<String, Integer> entry : counts.entrySet()) {            System.out.println(entry.getKey() + ": " + entry.getValue());        }    }}
Java Reference