Skip to lesson

Downstream collectors

A downstream collector is a second collector that you pass into groupingBy. Instead of storing each group as a list, groupingBy hands every group's elements to that collector, so you get a count, a sum, an average or a top element per group in one pass.

Passing a second collector into groupingBy

With one argument, groupingBy(Student::branch) stores each group as a List. Often you do not want the list at all: you want how many students each branch has, or their average marks.

Example 1 · Count per branch: two steps versus one

CountPerBranchDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int marks) {}
public class CountPerBranchDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 88),                new Student("Ravi", "ECE", 72),                new Student("Neha", "CSE", 91),                new Student("Imran", "MECH", 64),                new Student("Kiran", "ECE", 79),                new Student("Divya", "CSE", 70));
        // two steps: group into lists, then read each list's size        Map<String, List<Student>> lists = students.stream()                .collect(Collectors.groupingBy(Student::branch));        new TreeMap<>(lists).forEach((b, list) -> System.out.println(b + " has " + list.size()));
        // one step: a downstream collector counts each group        Map<String, Long> counts = students.stream()                .collect(Collectors.groupingBy(Student::branch, Collectors.counting()));        System.out.println(new TreeMap<>(counts));    }}
Output
CSE has 3
ECE has 2
MECH has 1
{CSE=3, ECE=2, MECH=1}

What this code does

  • The first version builds a list per branch only to throw it away after reading size(). The second passes Collectors.counting() as the downstream, so each group becomes a number straight away.
  • counting() produces a Long, so the map type is Map<String, Long>. The printout goes through a TreeMap to keep the branches in A to Z order.

The old way was two steps: group into lists, then loop over every list to count or add. groupingBy(classifier, downstream) does both in one pass. The downstream collector receives the elements of one group and builds that group's value. In fact, groupingBy(f) is just a short form of groupingBy(f, Collectors.toList()).

Think of it as a small collector running inside each group. The classifier decides the group; the downstream decides what the group turns into.

counting, summingInt and averagingDouble

These three answer the most common report questions. Each takes the elements of one group and returns one number.

Example 2 · Total and average per group

FeesAndCgpaDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int fees, double cgpa) {}
public class FeesAndCgpaDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 95000, 8.6),                new Student("Ravi", "ECE", 85000, 7.4),                new Student("Neha", "CSE", 95000, 9.1),                new Student("Kiran", "ECE", 80000, 8.0),                new Student("Divya", "CSE", 90000, 7.9));
        Map<String, Integer> feesByBranch = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.summingInt(Student::fees)));        Map<String, Double> avgCgpa = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.averagingDouble(Student::cgpa)));        Map<String, Double> avgFees = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.averagingInt(Student::fees)));
        for (String b : new TreeMap<>(feesByBranch).keySet()) {            System.out.printf("%s: fees collected Rs %d, average fee Rs %.1f, average CGPA %.2f%n",                    b, feesByBranch.get(b), avgFees.get(b), avgCgpa.get(b));        }    }}
Output
CSE: fees collected Rs 280000, average fee Rs 93333.3, average CGPA 8.53
ECE: fees collected Rs 165000, average fee Rs 82500.0, average CGPA 7.70

What this code does

  • summingInt(Student::fees) adds the fees inside each branch and gives an Integer. averagingDouble(Student::cgpa) gives each branch's mean CGPA as a Double.
  • averagingInt also returns a Double: the CSE fees 95000, 95000 and 90000 average to 93333.3, which an int could not hold. printf with %.2f keeps long decimals out of the report.

Example 3 · Trap: counting is a Long, not an Integer

CountTypeDemo.javaJava
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
record Student(String name, String branch) {}
public class CountTypeDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE"),                new Student("Ravi", "ECE"),                new Student("Neha", "CSE"));
        Map<String, Integer> counts = students.stream()                .collect(Collectors.groupingBy(Student::branch, Collectors.counting()));        System.out.println(counts);    }}
Sample compiler output
CountTypeDemo.java:15: error: incompatible types: inference variable D has incompatible equality constraints Integer,Long
                .collect(Collectors.groupingBy(Student::branch, Collectors.counting()));
                        ^
  where D,T,K,A are type-variables:
    D extends Object declared in method <T,K,A,D>groupingBy(Function<? super T,? extends K>,Collector<? super T,A,D>)
    T extends Object declared in method <T,K,A,D>groupingBy(Function<? super T,? extends K>,Collector<? super T,A,D>)
    K extends Object declared in method <T,K,A,D>groupingBy(Function<? super T,? extends K>,Collector<? super T,A,D>)
    A extends Object declared in method <T,K,A,D>groupingBy(Function<? super T,? extends K>,Collector<? super T,A,D>)
1 error

What this code does

  • D is the type of each group's value. The variable says Integer, but counting() produces Long, so Java reports two conflicting answers for D: "Integer,Long".
  • Fix it by declaring Map<String, Long>. If you really need int values, use summingInt(s -> 1), which counts by adding 1 per element and gives an Integer.
  • counting(): how many elements, as a Long. So the map is Map<String, Long>, not Map<String, Integer>.
  • summingInt(Student::fees): the total of an int field, as an Integer. summingLong and summingDouble also exist.
  • averagingDouble(Student::cgpa): the average, as a Double. averagingInt also returns a Double, because the average of whole numbers can have a decimal part.
  • A group is never empty inside groupingBy, so an average never divides by zero.
Writing Map<String, Integer> for counting() is a compile error ("incompatible equality constraints Integer,Long"). Use Map<String, Long>.

maxBy and minBy: the top element of each group

maxBy(comparator) keeps the largest element of each group by the comparator you give; minBy keeps the smallest. groupingBy(Student::branch, maxBy(Comparator.comparingInt(Student::marks))) finds the topper of each branch.

Example 4 · maxBy and minBy: topper and lowest of each branch

ToppersDemo.javaJava
import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int marks) {}
public class ToppersDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 88),                new Student("Ravi", "ECE", 72),                new Student("Neha", "CSE", 91),                new Student("Imran", "ECE", 79),                new Student("Kiran", "ECE", 79),                new Student("Divya", "CSE", 70));
        Comparator<Student> byMarks = Comparator.comparingInt(Student::marks);
        Map<String, Optional<Student>> toppers = students.stream()                .collect(Collectors.groupingBy(Student::branch, Collectors.maxBy(byMarks)));        Map<String, Optional<Student>> lowest = students.stream()                .collect(Collectors.groupingBy(Student::branch, Collectors.minBy(byMarks)));
        new TreeMap<>(toppers).forEach((branch, top) -> {            Student t = top.get();          // safe: a group is never empty            Student l = lowest.get(branch).get();            System.out.println(branch + " topper: " + t.name() + " (" + t.marks() + "), lowest: "                    + l.name() + " (" + l.marks() + ")");        });    }}
Output
CSE topper: Neha (91), lowest: Divya (70)
ECE topper: Imran (79), lowest: Ravi (72)

What this code does

  • maxBy(byMarks) keeps the highest-marks student of each group, minBy(byMarks) the lowest. The values are Optional<Student> because these collectors can also run on an empty stream; inside groupingBy the box always holds a student, so get() is safe.
  • Imran and Kiran tie on 79, the top ECE mark. maxBy keeps the first of equal elements, so Imran is the topper only because he comes first in the list. Add a thenComparing tie-breaker when the choice must not depend on input order.

The value type is Optional<Student>, not Student. An Optional is a box that may or may not hold a value. maxBy is a general collector that can also run on an empty stream, so it always returns a box. Inside groupingBy every group has at least one element, so the box is never empty and get() is safe there. The joining, mapping and filtering collectors lesson shows collectingAndThen, which removes the box. On a tie, maxBy and minBy keep the element that came first in the stream.

mapping and toSet inside a group

mapping(function, downstream) changes each element before it reaches the downstream collector, just like map on a stream. groupingBy(Student::branch, mapping(Student::city, toSet())) gives, for every branch, the set of cities its students come from.

Example 5 · mapping and toSet: cities per branch

CitiesPerBranchDemo.javaJava
import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeMap;import java.util.TreeSet;import java.util.stream.Collectors;
record Student(String name, String branch, String city) {}
public class CitiesPerBranchDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", "Pune"),                new Student("Ravi", "ECE", "Nagpur"),                new Student("Neha", "CSE", "Mumbai"),                new Student("Imran", "ECE", "Pune"),                new Student("Kiran", "CSE", "Pune"),                new Student("Divya", "ECE", "Nagpur"));
        Map<String, Set<String>> cities = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.mapping(Student::city, Collectors.toSet())));        new TreeMap<>(cities).forEach((b, set) ->                System.out.println(b + " students come from " + new TreeSet<>(set)));
        Map<String, TreeSet<String>> sortedCities = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.mapping(Student::city, Collectors.toCollection(TreeSet::new))));        System.out.println(new TreeMap<>(sortedCities));    }}
Output
CSE students come from [Mumbai, Pune]
ECE students come from [Nagpur, Pune]
{CSE=[Mumbai, Pune], ECE=[Nagpur, Pune]}

What this code does

  • mapping(Student::city, toSet()) turns each student into a city, then puts the cities into a set, so Pune appears once for CSE even though two CSE students live there.
  • Swapping toSet() for toCollection(TreeSet::new) makes each group's cities sorted, with no extra copy when printing. Downstream collectors can be nested like this as deep as you need.

Any collector can be the downstream: toSet() to remove repeats, toList() to keep them, toCollection(TreeSet::new) to sort them. Downstream collectors nest, so mapping itself takes a downstream collector.

Real-world use: total sales per category

An online shop's daily report asks: for each category, how many orders, how much revenue and what was the biggest order? Each question is one groupingBy with a different downstream collector: counting(), summingInt(Order::amount) and maxBy(comparingInt(Order::amount)).

Example 6 · Real world: daily sales report per category

SalesReportDemo.javaJava
import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;import java.util.stream.Collectors;
record Order(int id, String category, int amount) {}
public class SalesReportDemo {    public static void main(String[] args) {        List<Order> orders = List.of(                new Order(1, "Books", 450),                new Order(2, "Mobiles", 15999),                new Order(3, "Books", 299),                new Order(4, "Stationery", 120),                new Order(5, "Mobiles", 8999),                new Order(6, "Books", 650),                new Order(7, "Stationery", 80));
        Map<String, Long> count = orders.stream()                .collect(Collectors.groupingBy(Order::category, Collectors.counting()));        Map<String, Integer> revenue = orders.stream()                .collect(Collectors.groupingBy(Order::category, Collectors.summingInt(Order::amount)));        Map<String, Optional<Order>> biggest = orders.stream()                .collect(Collectors.groupingBy(Order::category,                        Collectors.maxBy(Comparator.comparingInt(Order::amount))));
        System.out.printf("%-11s %6s %9s %8s%n", "Category", "Orders", "Revenue", "Biggest");        for (String c : new TreeMap<>(revenue).keySet()) {            System.out.printf("%-11s %6d %9d %8d%n",                    c, count.get(c), revenue.get(c), biggest.get(c).get().amount());        }    }}
Output
Category    Orders   Revenue  Biggest
Books            3      1399      650
Mobiles          2     24998    15999
Stationery       2       200      120

What this code does

  • Three groupingBy calls with three different downstream collectors answer three questions about the same orders: how many, how much, and the biggest order of each category.
  • All three maps use the same keys, so one loop over the sorted category names can read each map with get. The Summary statistics and teeing lesson gets count, total and maximum from a single collector.

The same pattern works for attendance by month, expenses by type in a hostel budget, or runs by batter in a cricket season.

Next step

Check your understanding

11 quick questions