Reading history

Java Stream Collectors and groupingBy

6 min read 0 views

Group, count, average and summarise data with Java Collectors: groupingBy, partitioningBy, toMap with merge, summarizingInt, joining and teeing.

The last step of most stream pipelines is collect, and the Collectors class decides what you get back. Beyond simple lists, collectors can group students by department, count and average each group, split data into two parts, build maps with merged values, and compute statistics in one pass. This is the Java equivalent of SQL’s GROUP BY, and it turns many loops into one readable statement.

In this lesson you will learn

  • groupingBy with downstream collectors
  • counting, averagingDouble, maxBy and mapping
  • partitioningBy for true/false splits
  • toMap with a merge function, and nested grouping
  • summarizingInt, joining and teeing

You should know the Streams API, records and method references.

Grouping and Partitioning

import java.util.*;
import java.util.stream.*;

public class Main {
    record Student(String name, String dept, String city, double cgpa) {}

    public static void main(String[] args) {
        List<Student> students = List.of(
            new Student("Nusrat", "CSE", "Dhaka", 3.82),
            new Student("Arif", "EEE", "Chattogram", 3.41),
            new Student("Tania", "CSE", "Dhaka", 3.95),
            new Student("Imran", "BBA", "Khulna", 3.10),
            new Student("Mitu", "CSE", "Sylhet", 3.67),
            new Student("Rafi", "EEE", "Dhaka", 2.98),
            new Student("Sabbir", "BBA", "Rajshahi", 3.55));

        // groupingBy: a Map from key to List
        Map<String, List<String>> namesByDept = students.stream()
            .collect(Collectors.groupingBy(Student::dept, TreeMap::new,
                     Collectors.mapping(Student::name, Collectors.toList())));
        System.out.println(namesByDept);

        // Downstream collectors: count, average, max
        Map<String, Long> countByDept = students.stream()
            .collect(Collectors.groupingBy(Student::dept, TreeMap::new, Collectors.counting()));
        System.out.println(countByDept);

        Map<String, Double> avgByDept = students.stream()
            .collect(Collectors.groupingBy(Student::dept, TreeMap::new, Collectors.averagingDouble(Student::cgpa)));
        avgByDept.forEach((d, avg) -> System.out.printf("%s average %.2f%n", d, avg));

        Map<String, Optional<Student>> bestByDept = students.stream()
            .collect(Collectors.groupingBy(Student::dept, TreeMap::new,
                     Collectors.maxBy(Comparator.comparingDouble(Student::cgpa))));
        bestByDept.forEach((d, s) -> System.out.println(d + " best: " + s.get().name()));

        // partitioningBy: always exactly two groups, true and false
        Map<Boolean, List<String>> above35 = students.stream()
            .collect(Collectors.partitioningBy(s -> s.cgpa() >= 3.5,
                     Collectors.mapping(Student::name, Collectors.toList())));
        System.out.println("3.5 or more: " + above35.get(true));
        System.out.println("below 3.5  : " + above35.get(false));
    }
}

Output

{BBA=[Imran, Sabbir], CSE=[Nusrat, Tania, Mitu], EEE=[Arif, Rafi]}
{BBA=2, CSE=3, EEE=2}
BBA average 3.33
CSE average 3.81
EEE average 3.20
BBA best: Sabbir
CSE best: Tania
EEE best: Arif
3.5 or more: [Nusrat, Tania, Mitu, Sabbir]
below 3.5  : [Arif, Imran, Rafi]
  • groupingBy(classifier) builds a map from each key to the list of matching elements.
  • The optional middle argument, TreeMap::new, chooses the map type; a TreeMap keeps departments sorted.
  • The last argument is a downstream collector applied to each group: mapping keeps only names, counting counts, averagingDouble averages and maxBy finds the best.
  • maxBy returns an Optional, because in general a group could be empty.
  • partitioningBy always gives exactly two groups, keyed true and false.

toMap, Nested Groups and Statistics

import java.util.*;
import java.util.stream.*;

public class Main {
    record Sale(String product, String month, int qty, int price) {
        int total() { return qty * price; }
    }

    public static void main(String[] args) {
        List<Sale> sales = List.of(
            new Sale("Pen", "Jan", 40, 15), new Sale("Book", "Jan", 5, 350),
            new Sale("Pen", "Feb", 25, 15), new Sale("Bag", "Feb", 2, 1200),
            new Sale("Book", "Feb", 3, 350), new Sale("Pen", "Mar", 60, 15));

        // toMap with a merge function to add up duplicates
        Map<String, Integer> revenue = sales.stream()
            .collect(Collectors.toMap(Sale::product, Sale::total, Integer::sum, TreeMap::new));
        System.out.println("Revenue by product: " + revenue);

        // Nested grouping: month -> product -> qty
        Map<String, Map<String, Integer>> table = sales.stream()
            .collect(Collectors.groupingBy(Sale::month, LinkedHashMap::new,
                     Collectors.groupingBy(Sale::product, TreeMap::new, Collectors.summingInt(Sale::qty))));
        System.out.println("Qty by month: " + table);

        // Statistics in one pass
        IntSummaryStatistics stats = sales.stream().collect(Collectors.summarizingInt(Sale::total));
        System.out.println("count=" + stats.getCount() + " sum=" + stats.getSum()
            + " min=" + stats.getMin() + " max=" + stats.getMax() + " avg=" + stats.getAverage());

        // joining
        String products = sales.stream().map(Sale::product).distinct().sorted()
            .collect(Collectors.joining(", ", "[", "]"));
        System.out.println("Products: " + products);

        // teeing (Java 12+): two collectors at once, then combine
        double avgPrice = sales.stream().collect(Collectors.teeing(
            Collectors.summingInt(Sale::total),
            Collectors.summingInt(Sale::qty),
            (money, units) -> (double) money / units));
        System.out.printf("Average price per unit sold: %.2f%n", avgPrice);
    }
}

Output

Revenue by product: {Bag=2400, Book=2800, Pen=1875}
Qty by month: {Jan={Book=5, Pen=40}, Feb={Bag=2, Book=3, Pen=25}, Mar={Pen=60}}
count=6 sum=7075 min=375 max=2400 avg=1179.1666666666667
Products: [Bag, Book, Pen]
Average price per unit sold: 52.41
  • toMap(key, value, merge, mapFactory): when two sales share a product, Integer::sum adds their totals. Without a merge function, a duplicate key throws IllegalStateException.
  • A groupingBy inside a groupingBy builds a two-level table, like a pivot: month, then product, then quantity. LinkedHashMap::new keeps months in the order they appear.
  • summarizingInt gives count, sum, min, max and average in a single pass.
  • joining(", ", "[", "]") concatenates strings with a separator, prefix and suffix.
  • teeing runs two collectors on the same stream and combines their results: 7,075 taka ÷ 135 units ≈ 52.41 taka per unit.

SQL to Collectors

SQLCollectors
GROUP BY deptgroupingBy(Student::dept)
COUNT(*)counting()
AVG(cgpa), SUM(qty)averagingDouble(…), summingInt(…)
MAX(…)maxBy(comparator)
GROUP_CONCAT(name)mapping(Student::name, joining(", "))

Common Mistakes

  1. Using toMap without a merge function when keys can repeat.
  2. Expecting groupingBy to sort keys. The default is a HashMap; pass TreeMap::new for sorted output.
  3. Calling get() on maxBy results without thinking. It is safe inside groupingBy, but not in general.
  4. Writing a giant collector chain. Split it into named variables if it becomes hard to read.

Practice Exercises

Exercise 1. Using the students from the first program, build a map from city to the number of students, sorted by city.

Show answer
Map<String, Long> byCity = students.stream()
    .collect(Collectors.groupingBy(Student::city, TreeMap::new, Collectors.counting()));
// {Chattogram=1, Dhaka=3, Khulna=1, Rajshahi=1, Sylhet=1}

Exercise 2. Produce a single string of CSE students’ names separated by ” | “.

Show answer
String cse = students.stream()
    .filter(s -> s.dept().equals("CSE"))
    .map(Student::name)
    .collect(Collectors.joining(" | "));
// Nusrat | Tania | Mitu

Frequently Asked Questions

What is the difference between toList() and Collectors.toList()?

stream.toList() (Java 16+) returns an unmodifiable list. collect(Collectors.toList()) returns a list that, in practice, can be modified, but this is not guaranteed. Prefer toList() when you do not need to change the result.

Can groupingBy run in parallel?

Yes, with a parallel stream, but merging maps has a cost. groupingByConcurrent is designed for parallel streams; for small data, sequential streams are usually faster.

Summary

  • groupingBy(key, mapFactory, downstream) is Java’s GROUP BY.
  • Downstream collectors count, sum, average, find max or map values in each group.
  • partitioningBy splits into true and false.
  • toMap needs a merge function for repeated keys; teeing combines two collectors.

Next: Java TreeMap, LinkedHashMap and an LRU Cache.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *