Java Map.merge
Map.merge can initialize a count on the first scan and add one on later scans. LinkedHashMap keeps products in the order they first appeared.
A simple example
Map.merge
- Start with A, B, A
- Do this Count each key
- Result A has 2, B has 1
Syntax
counts.merge(code, 1, Integer::sum)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCount repeated product codes in input order
A reporting system receives a sequence of events or product codes with repetitions. Aggregate the values according to the required grouping and order so the report keeps the distinction between items and occurrences.
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Map<String, Integer> counts = new LinkedHashMap<>();
for (String code : List.of("B", "A", "B")) {
counts.merge(code, 1, Integer::sum);
}
System.out.println(counts);
}
}
{B=2, A=1}Use a LinkedHashMap to retain the order of first appearance. Map.merge inserts the initial count and adds to an existing count when a code repeats.
Combine two deliveries for the same shelf
Two suppliers drop off crates of tea during one shift. The first delivery establishes the shelf count, and the second must add to the count without replacing the earlier delivery.
import java.util.HashMap;
class Main {
public static void main(String[] args) throws Exception {
var crates = new HashMap<String, Integer>();
crates.merge("Tea", 3, Integer::sum);
crates.merge("Tea", 4, Integer::sum);
System.out.println(crates.get("Tea"));
}
}
7
The first merge inserts three. The second calls the addition function with three and four.
Count north-door returns
A gallery receives entrance codes from four ticket desks. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?
What to watch for
The combining function runs only when there is a previous non-null value.