Collectors: Gathering Results

Collectors: Gathering Results in Java: is the most powerful terminal operation. It takes the elements flowing through a stream and assembles them into whatever…

Concept Explanation

collect() is the most powerful terminal operation. It takes the elements flowing through a stream and assembles them into whatever structure you need — a list, a map, a summary, or a nested combination of all three.


The Basics

List<String> names = users.stream()
                          .map(User::getName)
                          .collect(Collectors.toList());

Set<String> unique = users.stream()
                          .map(User::getCity)
                          .collect(Collectors.toSet());

String joined = names.stream()
                     .collect(Collectors.joining(", ", "[", "]"));
// → [Ana, Ben, Chi]

Since Java 16, .toList() is shorter — note it returns an immutable list, whereas Collectors.toList() returns a mutable one.


Building Maps

Map<Long, User> byId = users.stream()
    .collect(Collectors.toMap(User::getId, u -> u));

// Duplicate keys throw IllegalStateException unless you supply a merge function
Map<String, Integer> totalByCity = orders.stream()
    .collect(Collectors.toMap(Order::getCity,
                              Order::getAmount,
                              Integer::sum));      // handles collisions

That third argument is not optional in practice — omit it and one duplicate key crashes your pipeline in production.


Grouping

This is where collectors become genuinely powerful:

// Simple grouping
Map<String, List<Employee>> byDept = employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment));

// Group and count
Map<String, Long> countByDept = employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment,
                                   Collectors.counting()));

// Group and average
Map<String, Double> avgSalary = employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment,
                                   Collectors.averagingDouble(Employee::getSalary)));

// Group and extract just the names
Map<String, List<String>> namesByDept = employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment,
                                   Collectors.mapping(Employee::getName,
                                                      Collectors.toList())));

// Two-level grouping
Map<String, Map<String, List<Employee>>> byDeptThenCity = employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment,
             Collectors.groupingBy(Employee::getCity)));

Splitting into exactly two groups has its own collector:

Map<Boolean, List<Employee>> split = employees.stream()
    .collect(Collectors.partitioningBy(e -> e.getSalary() > 50_000));

List<Employee> highEarners = split.get(true);

Summary Statistics

One pass, five numbers:

IntSummaryStatistics stats = employees.stream()
    .mapToInt(Employee::getAge)
    .summaryStatistics();

stats.getCount();  stats.getSum();  stats.getMin();
stats.getAverage(); stats.getMax();

Common Mistakes

  1. toMap without a merge function: Works in tests, throws on the first duplicate key in production.
  2. A null key in groupingBy: HashMap tolerates one null key, but toMap throws on a null value. Filter first.
  3. Assuming order in the result map: groupingBy returns a HashMap. Pass TreeMap::new if you need sorted keys.
  4. Collecting when you only need a number: count() beats collect(toList()).size().

Best Practices

  • .toList() for read-only results, Collectors.toList() when you must mutate.
  • Always supply a merge function to toMap.
  • Compose downstream collectors instead of collecting then re-streaming.
  • Name complex collectors: Extract a static final Collector with a descriptive name when the pipeline gets dense.

Practice Exercises

  1. The Report: Group a list of orders by customer and sum the amounts, producing Map<String, BigDecimal>.
  2. The Collision: Build a toMap with duplicate keys, watch it throw, then fix it with a merge function.
  3. The Two-Level Group: Group employees by department and then by city, and print the nested structure.