Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Map.merge()

Adds a value under a key or combines it with the existing one.

Available since: Java 8

Syntax

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

Parameters

ParameterTypeDescription
keyKThe key.
valueVThe value if the key is absent, and the second function argument if it is present.
remappingFunctionBiFunction<? super V, ? super V, ? extends V>Combines the old and new values; a `null` result removes the key.

Return value

VThe new value of the key, or `null` if the key was removed.

Examples

Counting repetitions:

void main() {
    Map<String, Integer> counts = new TreeMap<>();
    for (String fruit : List.of("apple", "pear", "apple", "kiwi", "apple")) {
        counts.merge(fruit, 1, Integer::sum);
    }
    IO.println(counts);
}

Output:

{apple=3, kiwi=1, pear=1}

Sales totals per manager:

void main() {
    record Sale(String who, double amount) {}
    var sales = List.of(new Sale("Anna", 120.5), new Sale("Oleg", 80), new Sale("Anna", 30));
    Map<String, Double> totals = new TreeMap<>();
    for (Sale s : sales) {
        totals.merge(s.who(), s.amount(), Double::sum);
    }
    IO.println(totals);
}

Output:

{Anna=150.5, Oleg=80.0}

Notes

If the key is absent, value is stored; if it is present, the result of the function on the old and new values is stored. It is the shortest way to keep counters and totals. A function returning null removes the key.

See also

Related recipes

In the tutorial

  • Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.

Thanks for reading!

Donate to the site — we work hard for you.