Java Collectors Class
What Collectors Provides
java.util.stream.Collectors is a utility class full of static methods that create ready-made collectors for stream.collect(...). The previous lesson used the simple ones — toList, toSet, toMap, joining. This lesson covers the collectors that make streams a reporting tool: grouping, partitioning, counting and aggregating per group, and combining collectors.
The key idea is the downstream collector: collectors like groupingBy split the elements into groups and then apply another collector to each group — count it, sum it, average it, collect names from it, find its maximum. Downstream collectors can be nested, which lets one pipeline compute what would otherwise need several loops and temporary maps.
The examples use this data class (compile it together with each example):
import java.util.*;
public class Data {
record Enrollment(String student, String city, String course, String level, int score, double fee, Set<String> skills) { }
static final List<Enrollment> ALL = List.of(
new Enrollment("Asha", "Chennai", "Java", "beginner", 91, 4999, Set.of("oop", "streams")),
new Enrollment("Ravi", "Madurai", "Java", "beginner", 45, 4999, Set.of("oop")),
new Enrollment("Meena", "Chennai", "Django", "intermediate", 77, 5999, Set.of("orm", "templates")),
new Enrollment("Kumar", "Salem", "Java", "advanced", 68, 6999, Set.of("streams", "concurrency")),
new Enrollment("Divya", "Madurai", "Docker", "intermediate", 39, 3999, Set.of("containers")),
new Enrollment("Asha", "Chennai", "Django", "intermediate", 88, 5999, Set.of("orm")),
new Enrollment("Priya", "Chennai", "Docker", "intermediate", 82, 3999, Set.of("containers", "compose")));
}
The examples use import static java.util.stream.Collectors.*;, so collectors can be written as groupingBy(...) instead of Collectors.groupingBy(...) — common practice for collector-heavy code.
groupingBy and Downstream Collectors
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class G1 {
public static void main(String[] args) {
var all = Data.ALL;
Map<String, List<Data.Enrollment>> byCourse = all.stream().collect(groupingBy(Data.Enrollment::course));
System.out.println("groups: " + new TreeMap<>(byCourse).keySet() + ", Java has " + byCourse.get("Java").size());
System.out.println("count: " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new, counting())));
System.out.println("revenue: " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new, summingDouble(Data.Enrollment::fee))));
System.out.println("avg: " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new, averagingInt(Data.Enrollment::score))));
System.out.println("names: " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new, mapping(Data.Enrollment::student, joining(" & ")))));
System.out.println("passed: " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new,
filtering(e -> e.score() >= 50, mapping(Data.Enrollment::student, toList())))));
System.out.println("skills: " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new,
flatMapping(e -> e.skills().stream(), toCollection(TreeSet::new)))));
System.out.println("top: " + all.stream().collect(groupingBy(Data.Enrollment::course, TreeMap::new,
collectingAndThen(maxBy(Comparator.comparingInt(Data.Enrollment::score)),
o -> o.map(Data.Enrollment::student).orElse("-")))));
System.out.println("nested: " + all.stream().collect(groupingBy(Data.Enrollment::city, TreeMap::new,
groupingBy(Data.Enrollment::course, TreeMap::new, counting()))));
}
}
Output:
groups: [Django, Docker, Java], Java has 3
count: {Django=2, Docker=2, Java=3}
revenue: {Django=11998.0, Docker=7998.0, Java=16997.0}
avg: {Django=82.5, Docker=60.5, Java=68.0}
names: {Django=Meena & Asha, Docker=Divya & Priya, Java=Asha & Ravi & Kumar}
passed: {Django=[Meena, Asha], Docker=[Priya], Java=[Asha, Kumar]}
skills: {Django=[orm, templates], Docker=[compose, containers], Java=[concurrency, oop, streams]}
top: {Django=Asha, Docker=Priya, Java=Asha}
nested: {Chennai={Django=2, Docker=1, Java=1}, Madurai={Docker=1, Java=1}, Salem={Java=1}}
The three forms of groupingBy
| Form | Result |
|---|---|
groupingBy(classifier) | Map<K, List<T>> — each key maps to the list of elements with that key (a HashMap, no key order) |
groupingBy(classifier, downstream) | Map<K, D> — the downstream collector is applied to each group |
groupingBy(classifier, mapFactory, downstream) | Same, with a chosen map type — TreeMap::new sorts the keys |
The classifier is a function that computes each element's group key (Enrollment::course). Only keys that actually occur become map entries.
Downstream collectors
| Collector | Per group, produces |
|---|---|
counting() | The number of elements (Long) |
summingInt/Long/Double(mapper) | The sum of a numeric property |
averagingInt/Long/Double(mapper) | The average (Double) |
minBy(cmp) / maxBy(cmp) | The smallest/largest element, as an Optional |
mapping(mapper, downstream) | Transforms each element, then collects with another collector |
filtering(predicate, downstream) (Java 9+) | Keeps matching elements, then collects |
flatMapping(mapper, downstream) (Java 9+) | Turns each element into a stream and collects all their elements |
joining(...) | Concatenated strings (after mapping to strings) |
toList(), toSet(), toCollection(...) | A collection of the group's elements |
collectingAndThen(downstream, finisher) | Applies a final transformation to the downstream result |
Points to notice in the output:
mappingcollects a property instead of whole objects — names per course, joined into a string.filteringversus filtering the stream first:filtering(e -> e.score() >= 50, ...)keeps every course key and filters within each group. Usingstream().filter(...)before grouping would make courses with no passing students disappear from the map entirely — sometimes that's wanted, often it isn't.flatMappingmerges the skills of all students in a course into one sorted set.maxByreturnsOptionalbecause a collector can't know a group is non-empty;collectingAndThenunwraps it into the student's name.- Multi-level grouping: a
groupingByas the downstream of anothergroupingByproduces a nested map — enrollments per course within each city.
Partitioning, Statistics and Combining Collectors
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class G2 {
public static void main(String[] args) {
var all = Data.ALL;
Map<Boolean, List<String>> passFail = all.stream()
.collect(partitioningBy(e -> e.score() >= 50, mapping(Data.Enrollment::student, toList())));
System.out.println("passed: " + passFail.get(true) + ", failed: " + passFail.get(false));
System.out.println("empty partitions exist: " + Stream.<Integer>empty().collect(partitioningBy(n -> n > 0)));
IntSummaryStatistics stats = all.stream().collect(summarizingInt(Data.Enrollment::score));
System.out.println(stats.getMin() + " " + stats.getMax() + " " + stats.getAverage() + " " + stats.getCount());
record Range(int low, int high) { }
Range r = all.stream().collect(teeing(
minBy(Comparator.comparingInt(Data.Enrollment::score)),
maxBy(Comparator.comparingInt(Data.Enrollment::score)),
(min, max) -> new Range(min.get().score(), max.get().score())));
System.out.println(r);
List<String> unmodifiable = all.stream().map(Data.Enrollment::course).distinct()
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
System.out.println(unmodifiable);
double revenue = all.stream().collect(reducing(0.0, Data.Enrollment::fee, Double::sum));
System.out.println(revenue);
java.util.stream.Collector<String, StringJoiner, String> bulleted = java.util.stream.Collector.of(
() -> new StringJoiner("\n"),
(j, s) -> j.add(" • " + s),
StringJoiner::merge,
StringJoiner::toString);
System.out.println(all.stream().map(Data.Enrollment::student).distinct().sorted().collect(bulleted));
}
}
Output:
passed: [Asha, Meena, Kumar, Asha, Priya], failed: [Ravi, Divya]
empty partitions exist: {false=[], true=[]}
39 91 70.0 7
Range[low=39, high=91]
[Java, Django, Docker]
36993.0
• Asha
• Divya
• Kumar
• Meena
• Priya
• Ravi
partitioningBy(predicate[, downstream])is a special grouping with exactly two groups, keyedtrueandfalse. UnlikegroupingBy, both keys are always present, even when a group is empty — sopassFail.get(false)never returnsnull.summarizingInt/Long/Doublecomputes count, sum, minimum, maximum and average in one pass, as anIntSummaryStatisticsobject.teeing(c1, c2, merger)(Java 12+) sends every element to two collectors and combines their results — here the minimum and maximum score in a single pass, packed into a local record.collectingAndThen(collector, finisher)post-processes a result, e.g. wrapping a list as unmodifiable.reducing(identity, mapper, op)is the collector form ofmap+reduce, mainly useful as a downstream collector.Collector.of(supplier, accumulator, combiner, finisher)creates a custom collector: supply a container (StringJoiner), add each element, merge two containers (for parallel streams) and convert to the final result. Here it formats a bulleted list.
Grouping Results Are Maps — Choose the Map Type
Without a map factory, groupingBy returns a HashMap, whose iteration order is unpredictable. For output that people read, or that tests compare, pass TreeMap::new (sorted keys) or LinkedHashMap::new (first-occurrence order). For enum keys, () -> new EnumMap<>(Level.class) is the fastest option and keeps declaration order.
Practical Example: A Course Dashboard
An admin dashboard shows one row per course: number of students, revenue, average score, pass rate and top student — plus a few headline figures. A single groupingBy with collectingAndThen builds a complete report record for each group.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Dash {
record CourseReport(String course, long students, double revenue, double average, double passRate, String topStudent) { }
public static void main(String[] args) {
Map<String, CourseReport> reports = Data.ALL.stream().collect(groupingBy(
Data.Enrollment::course,
TreeMap::new,
collectingAndThen(toList(), list -> new CourseReport(
list.get(0).course(),
list.size(),
list.stream().mapToDouble(Data.Enrollment::fee).sum(),
list.stream().mapToInt(Data.Enrollment::score).average().orElse(0),
100.0 * list.stream().filter(e -> e.score() >= 50).count() / list.size(),
list.stream().max(Comparator.comparingInt(Data.Enrollment::score)).map(Data.Enrollment::student).orElse("-")))));
System.out.printf("%-7s %8s %10s %7s %7s %s%n", "Course", "Students", "Revenue", "Avg", "Pass%", "Top");
reports.values().forEach(r -> System.out.printf("%-7s %8d %10.0f %7.1f %6.0f%% %s%n",
r.course(), r.students(), r.revenue(), r.average(), r.passRate(), r.topStudent()));
Map<String, Double> revenueByCity = Data.ALL.stream()
.collect(groupingBy(Data.Enrollment::city, summingDouble(Data.Enrollment::fee)));
String best = revenueByCity.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse("-");
Map<String, Long> repeatLearners = Data.ALL.stream()
.collect(collectingAndThen(groupingBy(Data.Enrollment::student, counting()),
m -> m.entrySet().stream().filter(e -> e.getValue() > 1)
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue))));
System.out.println("best city: " + best + " (" + revenueByCity.get(best) + ")");
System.out.println("repeat learners: " + repeatLearners);
}
}
Output:
Course Students Revenue Avg Pass% Top
Django 2 11998 82.5 100% Asha
Docker 2 7998 60.5 50% Priya
Java 3 16997 68.0 67% Asha
best city: Chennai (20996.0)
repeat learners: {Asha=2}
How it works:
- One group per course, sorted by name with
TreeMap::new. collectingAndThen(toList(), list -> new CourseReport(...))first collects each course's enrollments into a list, then turns that list into a report record. Inside the finisher, short streams over the group compute each column.list.get(0)is safe becausegroupingBynever creates empty groups.- The pass rate is computed as a percentage —
100.0 *comes first so the division happens in floating point, not integer arithmetic. - The report table is printed from the map's values, already in course order.
%%prints a literal percent sign. - Best city: revenue is summed per city, and the entry with the highest value wins.
- Repeat learners: students are counted, and
collectingAndThenfilters the resulting map to students with more than one enrollment — Asha, enrolled in both Java and Django.
Computing the same dashboard with loops would need several maps of running totals updated in one loop, or several separate loops. With collectors, each figure is declared where it's used, and the whole report is built in a single pipeline per question.