Stream groupingBy
Collectors.groupingBy turns a stream into a map from a key to the elements that share it, and a downstream collector decides what each group becomes: a list, a count, a total, a maximum or another map. This page explains how groupingBy works, runs the common downstream collectors and the newer filtering, flatMapping and teeing, and shows the traps with null keys, Optional results and result types.
Contents
How groupingBy works Basic grouping: lists, counts and totals Averages, maximums, nesting and partitions filtering, summarizing, joining and teeing Traps: null keys, Optionals and result types What groupingBy does underneath, and choosing the map Writing your own downstream collector Performance: groupingBy, loops and groupingByConcurrent Which collector to use
How groupingBy works
Collectors.groupingBytoList()groupingBy
It has three forms. groupingBy(classifier)Map<K, List<T>>groupingBy(classifier, downstream)groupingBy(classifier, mapFactory, downstream)TreeMap::new
| Collector | Since | Each group becomes |
|---|---|---|
toList()toSet()toCollection(...) | Java 8 | A collection of the elements |
counting() | Java 8 | A Long |
summingIntaveragingDoublesummarizingDouble | Java 8 | A total, an average, or all statistics |
mapping(f, downstream) | Java 8 | The downstream result of f |
maxByminBy | Java 8 | An Optional |
collectingAndThen(c, finisher) | Java 8 | The result of c |
filteringflatMapping | Java 9 | Only matching elements, or flattened ones |
teeing(c1, c2, merger) | Java 12 | Two results combined (also usable without grouping) |
The examples use a shared Sale
Basic grouping: lists, counts and totals
The sample data is six sales across three regions and three products, so both groupings by region and by product have groups of different sizes.
import java.util.List;
// Shared sample data for the examples on this page
public record Sale(String region, String product, int units, double price) {
public double revenue() {
return units * price;
}
public static List<Sale> sample() {
return List.of(
new Sale("north", "laptop", 3, 900.0),
new Sale("south", "phone", 10, 400.0),
new Sale("north", "phone", 4, 400.0),
new Sale("east", "laptop", 1, 950.0),
new Sale("south", "laptop", 2, 900.0),
new Sale("north", "tablet", 6, 300.0));
}
}
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class BasicGrouping {
public static void main(String[] args) {
List<Sale> sales = Sale.sample();
// Default: Map<key, List<element>>
Map<String, List<Sale>> byRegion = sales.stream()
.collect(Collectors.groupingBy(Sale::region));
System.out.println("north has " + byRegion.get("north").size() + " sales");
// Downstream collector: count per group (TreeMap for sorted keys)
Map<String, Long> countByRegion = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.counting()));
System.out.println("count: " + countByRegion);
// Sum per group
Map<String, Integer> unitsByProduct = sales.stream()
.collect(Collectors.groupingBy(Sale::product, TreeMap::new,
Collectors.summingInt(Sale::units)));
System.out.println("units: " + unitsByProduct);
// Keep only one field of each element
Map<String, List<String>> productsByRegion = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.mapping(Sale::product, Collectors.toList())));
System.out.println("products: " + productsByRegion);
}
}
Output:
north has 3 sales
count: {east=1, north=3, south=2}
units: {laptop=6, phone=14, tablet=6}
products: {east=[laptop], north=[laptop, phone, tablet], south=[phone, laptop]}
gave a list of sales per region;groupingBy(Sale::region) has 3.north replaced each list by its size, andcounting() by the total units per product.summingInt(Sale::units) kept only the product names in each group.mapping(Sale::product, toList()) as the map factory sorts the keys, which makes reports readable and output stable. The defaultTreeMap::new order is arbitrary.HashMap
Averages, maximums, nesting and partitions
The same sales are grouped with richer downstream collectors, the kind used for dashboards and reports.
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class RicherGrouping {
public static void main(String[] args) {
var sales = Sale.sample();
// Statistics in one pass
Map<String, Double> avgRevenue = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.averagingDouble(Sale::revenue)));
System.out.println("average revenue: " + avgRevenue);
// Best element per group (maxBy returns Optional)
Map<String, Optional<Sale>> biggest = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.maxBy(Comparator.comparingDouble(Sale::revenue))));
biggest.forEach((region, sale) ->
System.out.println("biggest in " + region + ": " + sale.get().product()));
// collectingAndThen unwraps the Optional (groups are never empty)
Map<String, String> topProduct = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingDouble(Sale::revenue)),
s -> s.orElseThrow().product())));
System.out.println("top product: " + topProduct);
// Distinct values per group
Map<String, Set<String>> regionsByProduct = sales.stream()
.collect(Collectors.groupingBy(Sale::product, TreeMap::new,
Collectors.mapping(Sale::region, Collectors.toCollection(TreeSet::new))));
System.out.println("sold in: " + regionsByProduct);
// Two levels: region -> product -> units
Map<String, Map<String, Integer>> nested = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new,
Collectors.groupingBy(Sale::product, TreeMap::new,
Collectors.summingInt(Sale::units))));
System.out.println("nested: " + nested);
// Two buckets only: partitioningBy
Map<Boolean, Long> bigOrders = sales.stream()
.collect(Collectors.partitioningBy(s -> s.revenue() >= 2000,
Collectors.counting()));
System.out.println("revenue >= 2000: " + bigOrders);
}
}
Output:
average revenue: {east=950.0, north=2033.3333333333333, south=2900.0}
biggest in east: laptop
biggest in north: laptop
biggest in south: phone
top product: {east=laptop, north=laptop, south=phone}
sold in: {laptop=[east, north, south], phone=[north, south], tablet=[north]}
nested: {east={laptop=1}, north={laptop=3, phone=4, tablet=6}, south={laptop=2, phone=10}}
revenue >= 2000: {false=4, true=2}
computed the mean revenue per region.averagingDouble(Sale::revenue) returns anmaxBy per group. Since a group always has at least one element,Optional safely unwraps it, giving the top product per region.collectingAndThen(maxBy(...), s -> s.orElseThrow().product()) listed the regions where each product sold.mapping(Sale::region, toSet())- A
inside agroupingBy built a two-level map: region, then product, then units.groupingBy splits into exactly two groups,partitioningBy andtrue , and always contains both keys.false
filtering, summarizing, joining and teeing
A second data set of orders, including a region where every order is small, shows the collectors added in Java 9 and 12 and a few useful combinations.
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class MoreCollectors {
record Order(String region, String product, double amount) {
}
public static void main(String[] args) {
List<Order> orders = List.of(new Order("north",
"laptop", 1200), new Order("north", "pen", 3),
new Order("south", "phone", 800), new Order("north", "phone", 750),
new Order("south", "pen", 2), new Order("east", "pen", 4));
// filtering (Java 9): keeps empty groups, unlike filter() before grouping
Map<String, List<String>> bigOnly = orders.stream().collect(Collectors.groupingBy(
Order::region, TreeMap::new, Collectors.filtering(o -> o.amount() > 100,
Collectors.mapping(Order::product, Collectors.toList()))));
Map<String, List<String>> filteredFirst = orders.stream().filter(o -> o.amount() > 100)
.collect(Collectors.groupingBy(Order::region, TreeMap::new,
Collectors.mapping(Order::product, Collectors.toList())));
System.out.println("filtering(): " + bigOnly);
System.out.println("filter() first: " + filteredFirst);
// summarizingDouble: count, sum, min, max and average in one pass
Map<String, DoubleSummaryStatistics> stats = orders.stream().collect(
Collectors.groupingBy(Order::region, TreeMap::new,
Collectors.summarizingDouble(Order::amount)));
DoubleSummaryStatistics north = stats.get("north");
System.out.printf("north: count %d, sum %.0f, max %.0f, avg %.1f%n", north.getCount(),
north.getSum(), north.getMax(), north.getAverage());
// mapping to a Set, and joining
Map<String, Set<String>> regionsPerProduct = orders.stream().collect(Collectors.groupingBy(
Order::product, TreeMap::new, Collectors.mapping(Order::region, Collectors.toSet())));
System.out.println("regions per product: " + regionsPerProduct);
Map<String, String> joined = orders.stream().collect(Collectors.groupingBy(Order::region,
TreeMap::new, Collectors.mapping(Order::product, Collectors.joining("+"))));
System.out.println("joined: " + joined);
// teeing (Java 12): two collectors over the same elements, combined at the end
String summary = orders.stream().collect(Collectors.teeing(
Collectors.counting(),
Collectors.summingDouble(Order::amount),
(count, total) -> count + " orders, total " + total));
System.out.println("teeing: " + summary);
}
}
Output:
filtering(): {east=[], north=[laptop, phone], south=[phone]}
filter() first: {north=[laptop, phone], south=[phone]}
north: count 3, sum 1953, max 1200, avg 651.0
regions per product: {laptop=[north], pen=[east, south, north], phone=[south, north]}
joined: {east=pen, north=laptop+pen+phone, south=phone+pen}
teeing: 6 orders, total 2759.0
filters inside each group, soCollectors.filtering , which has no order above 100, appears with an empty list. Filtering the stream before grouping removeseast from the map entirely. Choose based on whether reports should show empty groups.east collects count, sum, minimum, maximum and average in one pass, here 3 orders worth 1,953 insummarizingDouble .north gives distinct values per group, in no particular order, andmapping(..., toSet()) a single string per group.mapping(..., joining("+")) runs two collectors over the same elements and merges their results, here a count and a total in one pass without grouping at all.teeing
Traps: null keys, Optionals and result types
A person with no city is the kind of data that breaks grouping code in production. The program shows that failure and three other things to watch.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
public class GroupingTraps {
record Person(String name, String city) {
}
public static void main(String[] args) {
List<Person> people = Arrays.asList(new Person("ann", "Oslo"), new Person("bob", null),
new Person("cy", "Lima"));
// A null key throws
try {
people.stream().collect(Collectors.groupingBy(Person::city));
} catch (NullPointerException e) {
System.out.println("groupingBy with a null key: NullPointerException: "
+ e.getMessage());
}
Map<String, List<String>> safe = people.stream().collect(Collectors.groupingBy(
p -> Objects.requireNonNullElse(p.city(), "unknown"),
Collectors.mapping(Person::name, Collectors.toList())));
System.out.println("with a placeholder key: " + new java.util.TreeMap<>(safe));
// maxBy gives Optional values; collectingAndThen unwraps them
Map<String, Optional<Person>> withOptional = people.stream()
.filter(p -> p.city() != null)
.collect(Collectors.groupingBy(Person::city,
Collectors.maxBy(java.util.Comparator.comparing(Person::name))));
System.out.println("maxBy values are Optionals: " + withOptional.get("Oslo"));
// The default map and list types are not specified: ask for what you need
Map<String, List<String>> grouped = people.stream().filter(p -> p.city() != null)
.collect(Collectors.groupingBy(Person::city,
Collectors.mapping(Person::name, Collectors.toCollection(ArrayList::new))));
grouped.get("Oslo").add("dee"); // fine: we asked for ArrayList
System.out.println("mutable groups: " + grouped.get("Oslo"));
// counting() returns Long, not Integer
Map<String, Long> counts = people.stream().filter(p -> p.city() != null)
.collect(Collectors.groupingBy(Person::city, Collectors.counting()));
Long oslo = counts.get("Oslo");
System.out.println("counting() type: "
+ oslo.getClass().getSimpleName() + ", value " + oslo);
}
}
Output:
groupingBy with a null key: NullPointerException: element cannot be mapped to a null key
with a placeholder key: {Lima=[cy], Oslo=[ann], unknown=[bob]}
maxBy values are Optionals: Optional[Person[name=ann, city=Oslo]]
mutable groups: [ann, dee]
counting() type: Long, value 1
- A classifier that returns
throwsnull with "element cannot be mapped to a null key". Map missing keys to a placeholder such asNullPointerException , or filter those elements out first."unknown" andmaxBy produceminBy values, which must be unwrapped, for example withOptional .collectingAndThen- The documentation does not promise the type, mutability or thread-safety of the default map and lists. Ask explicitly: a map factory such as
, andTreeMap::new for groups you want to change later.toCollection(ArrayList::new) returnscounting() . Assigning it to anLong variable does not compile; useInteger ifsummingInt(x -> 1) counts are needed.Integer
For parallel streams, groupingByConcurrentConcurrentMap
What groupingBy does underneath, and choosing the map
A grouping collector is a loop over the elements with a map in the middle. For each element it computes the key, looks up that key's container with computeIfAbsent
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class LoopEquivalent {
public static void main(String[] args) {
List<Sale> sales = Sale.sample();
// What groupingBy(region, mapping(product, toList())) does, written as a loop
Map<String, List<String>> loop = new TreeMap<>();
for (Sale s : sales) {
loop.computeIfAbsent(s.region(), k -> new ArrayList<>()).add(s.product());
}
Map<String, List<String>> stream = sales.stream().collect(Collectors.groupingBy(
Sale::region, TreeMap::new, Collectors.mapping(Sale::product, Collectors.toList())));
System.out.println("loop: " + loop);
System.out.println("stream: " + stream + ", equal: " + loop.equals(stream));
// Keys in first-seen order instead of sorted
Map<String, Long> firstSeen = sales.stream().collect(Collectors.groupingBy(
Sale::region, LinkedHashMap::new, Collectors.counting()));
System.out.println("LinkedHashMap keys (first seen): " + firstSeen.keySet());
// Integer counts instead of Long
Map<String, Integer> intCounts = sales.stream().collect(Collectors.groupingBy(
Sale::product, TreeMap::new, Collectors.summingInt(s -> 1)));
System.out.println("summingInt(s -> 1): " + intCounts);
// A key made of two fields: group by region and product at once
record RegionProduct(String region, String product) {
}
Map<RegionProduct, Integer> units = sales.stream().collect(Collectors.groupingBy(
s -> new RegionProduct(s.region(), s.product()), Collectors.summingInt(Sale::units)));
System.out.println("north/phone units: " + units.get(new RegionProduct("north", "phone"))
+ " (" + units.size() + " region-product pairs)");
}
}
loop: {east=[laptop], north=[laptop, phone, tablet], south=[phone, laptop]}
stream: {east=[laptop], north=[laptop, phone, tablet], south=[phone, laptop]}, equal: true
LinkedHashMap keys (first seen): [north, south, east]
summingInt(s -> 1): {laptop=3, phone=2, tablet=1}
north/phone units: 4 (6 region-product pairs)
- The hand-written
loop and the collector gave equal maps,computeIfAbsent . Either is fine; the collector reads better once a downstream collector does real work.{east=[laptop], north=[laptop, phone, tablet], south=[phone, laptop]} - With
the keys came out asLinkedHashMap::new , the order in which each region first appeared in the data. Use it for reports that should follow the input order.[north, south, east] producedsummingInt(s -> 1) counts,Integer , for code that cannot take the{laptop=3, phone=2, tablet=1} values thatLong returns.counting()- A local record as the key grouped by two fields at once. The key for north and phone held 4 units, and the map had 6 entries, one per region and product pair. This is flatter than a nested
and easier to look up, because records supplygroupingBy andequals .hashCode
Choose a nested map when you will walk the result level by level, as in a report with a heading per region. Choose a record key when you will look up single combinations or sort them as one list.
Writing your own downstream collector
When no built-in collector answers the question, Collector.of
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class CustomCollector {
// Collects the n largest elements, largest first, keeping only n at a time
static <T> Collector<T, ?, List<T>> topN(int n, Comparator<? super T> cmp) {
return Collector.of(
() -> new PriorityQueue<T>(cmp), // supplier: a new container
(heap, t) -> { // accumulator: add one element
heap.add(t);
if (heap.size() > n) {
heap.poll();
}
},
(h1, h2) -> { // combiner: merge two containers
for (T t : h2) {
h1.add(t);
if (h1.size() > n) {
h1.poll();
}
}
return h1;
},
heap -> { // finisher: the final result
List<T> out = new ArrayList<>(heap);
out.sort(cmp.reversed());
return out;
});
}
public static void main(String[] args) {
List<Sale> sales = Sale.sample();
Map<String, List<String>> top2 = sales.stream().collect(Collectors.groupingBy(
Sale::region, TreeMap::new,
Collectors.collectingAndThen(topN(2, Comparator.comparingDouble(Sale::revenue)),
list -> list.stream().map(s -> s.product() + "=" + s.revenue()).toList())));
System.out.println("top 2 sales per region: " + top2);
// The same collector works on a parallel stream: the combiner merges partial results
List<Integer> top3 = java.util.stream.IntStream.range(0, 100000).boxed().parallel()
.collect(topN(3, Comparator.naturalOrder()));
System.out.println("top 3 of 0..99,999 in parallel: " + top3);
}
}
top 2 sales per region: {east=[laptop=950.0], north=[laptop=2700.0, tablet=1800.0], south=[phone=4000.0, laptop=1800.0]}
top 3 of 0..99,999 in parallel: [99999, 99998, 99997]
- North kept its two largest sales,
andlaptop=2700.0 , and dropped the phone sale worth 1,600. South kepttablet=1800.0 andphone=4000.0 .laptop=1800.0 - East had only one sale, so its list holds one entry. A top N collector should never invent entries or fail when a group is smaller than N.
- On a parallel stream of 100,000 numbers the result was
. Each thread filled its own heap, and the combiner merged them; a wrong combiner is the usual reason a custom collector works sequentially but gives wrong answers in parallel.[99999, 99998, 99997] - The heap is a min-heap under the comparator, so
removes the smallest of the kept elements. The finisher sorts the survivors with the reversed comparator so the largest comes first.poll
In practice the combiner runs only when a stream is parallel, so test any custom collector with parallel()Collector.ofIDENTITY_FINISH
Performance: groupingBy, loops and groupingByConcurrent
Counting words is the classic grouping job. The program counts 2,000,000 strings that share 1,000 distinct keys in five ways. Each figure is the fastest of three runs, taken from a second round so the first round can warm up the JIT compiler.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class GroupingSpeed {
static boolean print;
public static void main(String[] args) {
// 2,000,000 words drawn from 1,000 distinct keys
List<String> words = IntStream.range(0, 2000000)
.mapToObj(i -> "w" + (i % 1000 * 7919 % 1000)).toList();
System.out.printf("count %,d words with 1,000 distinct keys (best of 3, second round)%n",
words.size());
for (int round = 0; round < 2; round++) {
print = round == 1;
time("loop with merge", words, w -> {
Map<String, Long> m = new HashMap<>();
for (String s : w) {
m.merge(s, 1L, Long::sum);
}
return m;
});
time("groupingBy + counting", words, w -> w.stream()
.collect(Collectors.groupingBy(s -> s, Collectors.counting())));
time("toMap with merge function", words, w -> w.stream()
.collect(Collectors.toMap(s -> s, s -> 1L, Long::sum)));
time("parallel groupingBy", words, w -> w.parallelStream()
.collect(Collectors.groupingBy(s -> s, Collectors.counting())));
time("parallel groupingByConcurrent", words, w -> w.parallelStream()
.collect(Collectors.groupingByConcurrent(s -> s, Collectors.counting())));
}
}
static void time(String name, List<String> words, Function<List<String>, Map<String, Long>> f) {
long best = Long.MAX_VALUE;
Map<String, Long> result = null;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
result = f.apply(words);
best = Math.min(best, System.nanoTime() - t0);
}
if (print) {
System.out.printf(" %-30s %6.1f ms (w0 -> %d)%n", name, best / 1e6,
result.get("w0"));
}
}
}
Output (rough timings, 2-CPU Linux machine, JDK 21; the parallel lines vary most between runs):
count 2,000,000 words with 1,000 distinct keys (best of 3, second round)
loop with merge 28.5 ms (w0 -> 2000)
groupingBy + counting 26.5 ms (w0 -> 2000)
toMap with merge function 34.1 ms (w0 -> 2000)
parallel groupingBy 27.3 ms (w0 -> 2000)
parallel groupingByConcurrent 53.0 ms (w0 -> 2000)
- The
loop andmerge withgroupingBy finished within a few percent of each other in every run. Choose between them for readability, not speed.counting() withtoMap was about 1.3 to 1.6 times slower thanLong::sum across runs, because it boxes a newgroupingBy for each element before merging.Long- Plain
on a parallel stream ranged from about the same speed as the sequential version to about 1.8 times faster, depending on the run, on two CPUs. Each thread builds its own map, and the maps are merged at the end.groupingBy was the slowest, 2 to 3 times slower than sequentialgroupingByConcurrent . All threads share onegroupingBy , and becauseConcurrentHashMap is not a concurrent collector, the JDK 21 source wraps each update to a group incounting() on that group's container. With only 1,000 keys, threads keep meeting on the same locks.synchronized
groupingByConcurrent
Which collector to use
| Question per group | Downstream collector |
|---|---|
| Which elements? | Default toList() |
| How many? | counting() |
| Total or average of a field? | summingIntaveragingDouble |
| All statistics at once? | summarizingDouble |
| Only one field of each element? | mapping(field, toList()) |
| Distinct values? | mapping(field, toSet()) |
| The best element? | collectingAndThen(maxBy(cmp), Optional::orElseThrow) |
| Only some elements, keeping empty groups? | filtering(test, ...) |
| A second level of grouping? | Another groupingBy |
| Two answers in one pass? | teeing |
| Sorted keys? | Add TreeMap::new |
Flattening inside groups uses flatMappingEnumMap