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
Syntax
map.merge(key, value, remappingFunction)
Parameters
| Parameter | Description |
|---|---|
keyK |
The key. |
valueV |
Value to insert or combine. |
remappingFunctionBiFunction |
How to combine old and new, e.g. Integer::sum. |
Return value
The new value.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
map.getOrDefault()· Return the value for a key, or a default value if the key isn't present. Avoids null checks.stream.collect(Collectors.groupingBy())· Group elements into a Map by a key function, optionally counting or summing each group.- Java HashMap · tutorial