Java Downstream Collectors: counting, mapping, filtering, teeing and More
Process the groups of a Java groupingBy with downstream collectors: counting, summingInt, averagingInt, maxBy, mapping, joining, filtering, flatMapping, collectingAndThen, summarizingInt, reducing, nested groupingBy and teeing for two results in one pass.
kvi5hnuCode Sprout team member7 min readOn this page
A plain groupingBy gives you a map whose values are lists of elements. Usually you want something else per group: a count, a total, the largest element, just the names, or a comma-separated string. You get these by passing a downstream collector as the second argument. The downstream collector receives only the elements of one group and produces that group's value.
The examples use a small record and assume a static import of the collector factories, which keeps nested expressions readable:
import static java.util.stream.Collectors.*;
record City(String name, String state, int population) {}
Changing the collection
The simplest downstream collectors just pick a different container. For sets instead of lists:
Map<String, Set<Locale>> countryToLocaleSet = locales.collect(groupingBy(Locale::getCountry, toSet()));
toCollection(TreeSet::new), toUnmodifiableList() and the other collectors from article 8 work the same way.
Numbers per group
| Downstream collector | Group value | SQL equivalent |
|---|---|---|
counting() | Long: the number of elements | COUNT(*) |
summingInt(f), summingLong(f), summingDouble(f) | Integer/Long/Double: the sum of f | SUM |
averagingInt(f), averagingLong(f), averagingDouble(f) | always a Double: the average of f | AVG |
maxBy(comparator), minBy(comparator) | Optional<T>: the largest or smallest element | MAX, MIN |
summarizingInt(f) and friends | IntSummaryStatistics: all of the above at once |
Map<String, Long> citiesPerState = cities.collect(groupingBy(City::state, counting()));
Map<String, Integer> statePopulation = cities.collect(groupingBy(City::state, summingInt(City::population)));
Map<String, Optional<City>> largestCity = cities.collect(
groupingBy(City::state, maxBy(Comparator.comparingInt(City::population))));
Two type details catch people out. counting() produces a Long, not an Integer, so the map is Map<String, Long>. The averaging collectors always produce a Double, even for averagingInt. Watch out for summingInt as well: it adds in int arithmetic and silently overflows past about 2.1 billion. Use summingLong for large totals.
Post-processing with collectingAndThen
Why does maxBy give an Optional, when a group obviously has at least one element? Because maxBy is a general collector that could also run on an empty stream. Inside groupingBy the Optional is never empty, so you can safely unwrap it with collectingAndThen, which adds a finishing function after a collector:
Map<String, String> largestCityName = cities.collect(groupingBy(City::state,
collectingAndThen(maxBy(Comparator.comparingInt(City::population)), c -> c.orElseThrow().name())));
Another typical use is counting distinct values: collect into a set, then take its size with collectingAndThen(toSet(), Set::size).
Transforming elements: mapping and flatMapping
collectingAndThen transforms the result. mapping goes the other way and transforms each element before passing it on to another downstream collector:
Map<String, List<String>> names = cities.collect(groupingBy(City::state, mapping(City::name, toList())));
Map<String, String> joined = cities.collect(groupingBy(City::state, mapping(City::name, joining(", "))));
This finally gives the clean solution to the "languages per country" problem from article 9:
Map<String, Set<String>> countryToLanguages = locales.collect(
groupingBy(Locale::getDisplayCountry, mapping(Locale::getDisplayLanguage, toSet())));
flatMapping (Java 9) is the collector version of flatMap. The function returns a stream for each element, and all of those streams' elements go downstream. For example, collect every tag of every article in each category with groupingBy(Article::category, flatMapping(a -> a.tags().stream(), toSet())).
Filtering within groups
filtering (Java 9) passes only the matching elements downstream. Compare it with filtering before grouping:
cities.collect(groupingBy(City::state, filtering(c -> c.population() > 500_000, toList())));
// every state appears; Vermont maps to []
cities.filter(c -> c.population() > 500_000).collect(groupingBy(City::state));
// Vermont doesn't appear at all
Use filtering when every group should appear in the result, even with an empty value.
Nesting
A downstream collector can itself be a groupingBy or partitioningBy, giving maps of maps:
Map<String, Map<String, List<Locale>>> countryAndLanguageToLocale = locales.collect(
groupingBy(Locale::getCountry, groupingBy(Locale::getLanguage)));
Map<String, Map<Boolean, Long>> bigAndSmall = cities.collect(
groupingBy(City::state, partitioningBy(c -> c.population() > 500_000, counting())));
General reductions: reducing
The reducing collectors perform a general reduction as a downstream step. reducing(identity, mapper, op) maps each element and combines the results, for example reducing(0, City::population, Integer::max) for the maximum population per state. They're rarely needed: the specialized collectors above, or mapping with joining, are usually clearer. Article 13 explains reductions in detail.
Two results in one pass: teeing
A stream can be traversed only once. When you need two different results, such as a list of names and an average, teeing (Java 12) sends every element to two downstream collectors and combines their results with a function:
record Pair<S, T>(S first, T second) {}
Pair<List<String>, Double> nevada = cities.filter(c -> c.state().equals("NV"))
.collect(teeing(
mapping(City::name, toList()), // first downstream collector
averagingDouble(City::population), // second downstream collector
Pair::new)); // combines the two results
The name comes from a T-shaped pipe fitting that splits one flow into two. teeing(minBy(...), maxBy(...), ...) finding the range of values in one pass is another classic use.
A complete example
The city populations are rounded figures, just to have some data.
import static java.util.stream.Collectors.*;
import java.util.*;
import java.util.stream.*;
public class Solution {
record City(String name, String state, int population) {}
static Stream<City> cities() {
return Stream.of(new City("Las Vegas", "NV", 660_000), new City("Henderson", "NV", 330_000),
new City("Reno", "NV", 270_000), new City("New York", "NY", 8_260_000),
new City("Buffalo", "NY", 275_000), new City("Rochester", "NY", 210_000),
new City("Austin", "TX", 980_000), new City("Houston", "TX", 2_310_000),
new City("Dallas", "TX", 1_300_000), new City("Waco", "TX", 145_000),
new City("Burlington", "VT", 45_000));
}
record Pair<S, T>(S first, T second) {}
public static void main(String[] args) {
// toSet and counting as downstream collectors
Map<String, Long> citiesPerState = cities().collect(groupingBy(City::state, TreeMap::new, counting()));
System.out.println("cities per state: " + citiesPerState);
// summing and averaging
Map<String, Integer> statePopulation = cities()
.collect(groupingBy(City::state, TreeMap::new, summingInt(City::population)));
System.out.println("population: " + statePopulation);
Map<String, Double> averagePopulation = cities()
.collect(groupingBy(City::state, TreeMap::new, averagingInt(City::population)));
System.out.println("average: " + averagePopulation);
// maxBy gives an Optional; collectingAndThen unwraps it
Map<String, Optional<City>> largestOptional = cities()
.collect(groupingBy(City::state, TreeMap::new, maxBy(Comparator.comparingInt(City::population))));
System.out.println("largest in VT: " + largestOptional.get("VT"));
Map<String, String> largest = cities().collect(groupingBy(City::state, TreeMap::new,
collectingAndThen(maxBy(Comparator.comparingInt(City::population)), c -> c.orElseThrow().name())));
System.out.println("largest: " + largest);
// mapping: names only
Map<String, List<String>> names = cities()
.collect(groupingBy(City::state, TreeMap::new, mapping(City::name, toList())));
System.out.println("names: " + names);
// mapping with joining
Map<String, String> joined = cities()
.collect(groupingBy(City::state, TreeMap::new, mapping(City::name, joining(", "))));
System.out.println("NY joined: " + joined.get("NY"));
// collectingAndThen: number of distinct name lengths per state
Map<String, Integer> distinctLengths = cities().collect(groupingBy(City::state, TreeMap::new,
collectingAndThen(mapping(c -> c.name().length(), toSet()), Set::size)));
System.out.println("distinct name lengths: " + distinctLengths);
// filtering keeps empty groups; filter before grouping drops them
Map<String, List<String>> bigCities = cities().collect(groupingBy(City::state, TreeMap::new,
filtering(c -> c.population() > 500_000, mapping(City::name, toList()))));
System.out.println("big cities (filtering): " + bigCities);
Map<String, List<String>> bigCities2 = cities().filter(c -> c.population() > 500_000)
.collect(groupingBy(City::state, TreeMap::new, mapping(City::name, toList())));
System.out.println("big cities (filter first): " + bigCities2);
// flatMapping: the distinct letters used in each state's city names
Map<String, Set<Character>> letters = cities().collect(groupingBy(City::state, TreeMap::new,
flatMapping(c -> c.name().toLowerCase().chars().filter(Character::isLetter).mapToObj(ch -> (char) ch),
toCollection(TreeSet::new))));
System.out.println("letters in VT: " + letters.get("VT"));
// summary statistics per group
Map<String, IntSummaryStatistics> stats = cities()
.collect(groupingBy(City::state, TreeMap::new, summarizingInt(City::population)));
System.out.println("TX stats: " + stats.get("TX"));
// nested grouping: state, then size class
Map<String, Map<Boolean, Long>> bigAndSmall = cities().collect(groupingBy(City::state, TreeMap::new,
partitioningBy(c -> c.population() > 500_000, counting())));
System.out.println("big/small counts: " + bigAndSmall);
// reducing: general reduction downstream
Map<String, Integer> maxPopulation = cities().collect(groupingBy(City::state, TreeMap::new,
reducing(0, City::population, Integer::max)));
System.out.println("max population: " + maxPopulation);
// teeing: two results in one pass
Pair<List<String>, Double> nevada = cities().filter(c -> c.state().equals("NV"))
.collect(teeing(mapping(City::name, toList()), averagingDouble(City::population), Pair::new));
System.out.println("Nevada: " + nevada);
var range = Stream.of(5, 3, 9, 1, 7).collect(teeing(
minBy(Comparator.<Integer>naturalOrder()), maxBy(Comparator.<Integer>naturalOrder()),
(min, max) -> min.orElseThrow() + ".." + max.orElseThrow()));
System.out.println("range: " + range);
}
}
cities per state: {NV=3, NY=3, TX=4, VT=1}
population: {NV=1260000, NY=8745000, TX=4735000, VT=45000}
average: {NV=420000.0, NY=2915000.0, TX=1183750.0, VT=45000.0}
largest in VT: Optional[City[name=Burlington, state=VT, population=45000]]
largest: {NV=Las Vegas, NY=New York, TX=Houston, VT=Burlington}
names: {NV=[Las Vegas, Henderson, Reno], NY=[New York, Buffalo, Rochester], TX=[Austin, Houston, Dallas, Waco], VT=[Burlington]}
NY joined: New York, Buffalo, Rochester
distinct name lengths: {NV=2, NY=3, TX=3, VT=1}
big cities (filtering): {NV=[Las Vegas], NY=[New York], TX=[Austin, Houston, Dallas], VT=[]}
big cities (filter first): {NV=[Las Vegas], NY=[New York], TX=[Austin, Houston, Dallas]}
letters in VT: [b, g, i, l, n, o, r, t, u]
TX stats: IntSummaryStatistics{count=4, sum=4735000, min=145000, average=1183750.000000, max=2310000}
big/small counts: {NV={false=2, true=1}, NY={false=2, true=1}, TX={false=1, true=3}, VT={false=1, true=0}}
max population: {NV=660000, NY=8260000, TX=2310000, VT=45000}
Nevada: Pair[first=[Las Vegas, Henderson, Reno], second=420000.0]
range: 1..9
Every groupingBy passes TreeMap::new so that the states print in alphabetical order.
Common questions
How do I get the top 3 elements of each group?
Collect each group into a list and post-process it: groupingBy(City::state, collectingAndThen(toList(), list -> list.stream().sorted(comparing(City::population).reversed()).limit(3).toList())).
How do I sum BigDecimal amounts per group?
There is no summingBigDecimal, but reducing does the job exactly, without floating-point errors: groupingBy(Order::customer, reducing(BigDecimal.ZERO, Order::amount, BigDecimal::add)).
I want an Integer count instead of a Long. How?
collectingAndThen(counting(), Long::intValue), or summingInt(x -> 1). Only do this when the count can never exceed Integer.MAX_VALUE.
What does averagingInt return for an empty group?
0.0. Inside groupingBy there are no empty groups, but with filtering or partitioningBy there can be, and an average of 0 may be misleading. Use summarizingInt and check getCount() if that matters.
Should I use teeing or simply run two pipelines?
Two pipelines over a list are often clearer and only slightly slower. teeing matters when the source can be traversed only once (a file, a generator) or is very expensive to produce.
How do I make the result of a nested groupingBy easier to work with?
Map-of-map types such as Map<String, Map<Boolean, List<City>>> are hard to read. Consider grouping by a record key, or converting the result into a small record per group with collectingAndThen.
API reference
java.util.stream.Collectors
| Method | Description |
|---|---|
counting() | counts the elements, as a Long |
summingInt(ToIntFunction), summingLong(...), summingDouble(...) | sums the mapped values |
averagingInt(ToIntFunction), averagingLong(...), averagingDouble(...) | averages the mapped values, as a Double (0 for no elements) |
maxBy(Comparator), minBy(Comparator) | an Optional with the largest or smallest element |
collectingAndThen(Collector downstream, Function finisher) | applies finisher to the result of downstream |
mapping(Function mapper, Collector downstream) | maps each element, then collects with downstream |
flatMapping(Function<T, Stream<U>> mapper, Collector downstream) (Java 9) | sends the elements of each mapped stream to downstream |
filtering(Predicate predicate, Collector downstream) (Java 9) | sends only matching elements to downstream |
reducing(T identity, BinaryOperator<T> op), reducing(BinaryOperator<T> op), reducing(U identity, Function mapper, BinaryOperator<U> op) | general reductions (article 13) |
teeing(Collector downstream1, Collector downstream2, BiFunction merger) (Java 12) | collects with both collectors and merges the two results |
Summary
- A downstream collector, the second argument of
groupingByorpartitioningBy, decides what each group's value is. counting,summingX,averagingX,maxBy,minByandsummarizingXgive numbers per group.counting()is aLongand averages areDoubles.mapping,flatMappingandfilteringtransform or select elements before another collector.collectingAndThentransforms the final result.- Downstream collectors can nest, producing maps of maps.
teeingcomputes two results in a single pass and merges them.- Use composed collectors for grouping, and plain stream methods otherwise.
Practice Questions
Write a collector that maps each word's first letter to the number of words starting with it. What's the map's value type?
words.collect(groupingBy(w -> w.charAt(0), counting())) gives a Map<Character, Long>. counting() always produces Long.
Why does groupingBy(City::state, maxBy(...)) produce Optional values, and how do you get plain City values?
maxBy is general-purpose and returns an Optional in case there are no elements. Within groupingBy, every group has at least one element, so wrap it: collectingAndThen(maxBy(cmp), Optional::orElseThrow).
What's the difference between filtering(pred, toList()) as a downstream collector and calling filter(pred) before groupingBy?
With filtering, every key still appears, and groups without matches map to an empty list. With filter first, keys whose elements were all removed don't appear in the map at all.
Produce a Map<String, String> from each department to a comma-separated list of employee names.
employees.collect(groupingBy(Employee::department, mapping(Employee::name, joining(", ")))).
You need both the count and the total salary of all employees, in a single pass. Which collector helps, and what would the call look like?
teeing: employees.collect(teeing(counting(), summingLong(Employee::salary), (count, total) -> new Stats(count, total))), where Stats is a record. (summarizingLong(Employee::salary) would also give both in one object.)
Previous: Java groupingBy and partitioningBy: Grouping Stream Elements
Related reading
- Java groupingBy and partitioningBy: Grouping Stream Elements
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.