Java Collectors.groupingBy
Group records that share a key, then count or sum each group. A sales report can group events by region or successful orders by customer.
A simple example
Collectors.groupingBy
- Start with A, B, A
- Do this Count each key
- Result A has 2, B has 1
Syntax
Collectors.groupingBy(keyFunction, TreeMap::new, Collectors.counting())
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCount events by region in key 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.List;
import java.util.TreeMap;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) throws Exception {
var counts = List.of("west", "east", "east").stream()
.collect(Collectors.groupingBy(s -> s, TreeMap::new, Collectors.counting()));
counts.forEach((region, n) -> System.out.println(region + "=" + n));
System.out.println(counts.getOrDefault("north", 0L));
}
}
east=2 west=1 0
Specifying a TreeMap makes the printed key order predictable. A region with no events has no entry, so getOrDefault supplies the count for a lookup.
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?
Count ready print jobs
A print desk groups the current jobs by status. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?
What to watch for
Pick the map type deliberately when the printed order of groups matters.