Java 25 (LTS) reference · Map and HashMap Methods

Java Map merge() Method

Combine a value into the map: insert it if the key is missing, otherwise apply a function to the old and new values.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.merge(key, value, remappingFunction)

Parameters

ParameterDescription
key
K
The key.
value
V
Value to insert or combine.
remappingFunction
BiFunction
How to combine old and new, e.g. Integer::sum.

Return value

The new value.

Examples

Word counts in one line
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> counts = new TreeMap<>();
        for (String w : "the cat and the hat".split(" ")) counts.merge(w, 1, Integer::sum);
        System.out.println(counts);
    }
}

Output

{and=1, cat=1, hat=1, the=2}

Run this on your computer — see “Get Started” for setup.

Sum per customer
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Double> totals = new TreeMap<>();
        String[][] orders = {{"ana", "20.5"}, {"ben", "10"}, {"ana", "4.5"}};
        for (String[] o : orders) totals.merge(o[0], Double.parseDouble(o[1]), Double::sum);
        System.out.println(totals);
    }
}

Output

{ana=25.0, ben=10.0}

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?