Collectors brought grouping to Java

Java 8 Course · lesson 11 of 16 · 4 min read

The single addition that replaced the most hand-written code in enterprise Java.

Open this lesson in the learning hub

Key points

  • Grouping a list by a field used to be eight lines with a Map, a null check and a new ArrayList.
  • Collectors.groupingBy made it one expression, and it reads like the sentence you would say out loud.
  • A downstream collector reshapes each group - count them, sum them, or map them to another field.
  • toMap throws on duplicate keys unless you supply a merge function; that is a feature, not a bug.
  • partitioningBy always returns both true and false keys, even when one side is empty.

Example

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

public class Main {
    record Employee(String name, String dept, double salary) { }

    public static void main(String[] args) {
        List<Employee> staff = List.of(
            new Employee("Ada",   "eng",   120),
            new Employee("Bob",   "sales",  80),
            new Employee("Cleo",  "eng",   140),
            new Employee("Dan",   "sales",  90));

        System.out.println("by dept    : " +
            staff.stream().collect(Collectors.groupingBy(Employee::dept,
                    Collectors.mapping(Employee::name, Collectors.toList()))));

        System.out.println("headcount  : " +
            staff.stream().collect(Collectors.groupingBy(Employee::dept, Collectors.counting())));

        System.out.println("payroll    : " +
            staff.stream().collect(Collectors.groupingBy(Employee::dept,
                    Collectors.summingDouble(Employee::salary))));

        System.out.println("well paid? : " +
            staff.stream().collect(Collectors.partitioningBy(e -> e.salary() > 100,
                    Collectors.counting())));
    }
}

groupingBy plus a downstream collector expresses in one line what used to be a whole method.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 8 Course course, and every lesson in it is listed on the Java 8 Course contents page.