00:00

Collectors.collectingAndThen() in Java

Last updated:

Collectors.collectingAndThen() is a static method of java.util.stream.Collectors, available since Java 8, that wraps a collector and applies a finishing function to its result. It lets you post-process the collected value, for example to make a list unmodifiable, unwrap an Optional, or turn a list into its size, all inside the same collector.

This is especially useful as a downstream collector, where you cannot call a method on each group's result directly. This tutorial covers the signature and the most common finishing functions.

1. Syntax and Method Signature

Collectors.java (API)
// java.util.stream.Collectors (Java 8)
static <T, A, R, RR> Collector<T, A, RR> collectingAndThen(
        Collector<T, A, R> downstream,
        Function<R, RR> finisher)

downstream produces a result of type R, and the finisher function converts it to RR. The finisher runs once per result, after all elements have been collected.

Usage
List<String> readOnly = names.stream()
        .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));

2. How collectingAndThen() Works

collectingAndThen() returns a new collector that uses the downstream collector's supplier, accumulator and combiner unchanged and adds your function to the end of its finisher. The finishing step therefore runs exactly once per result: once for the whole stream at the top level, or once per group inside groupingBy().

collectingAndThen() runs a finisher on the collected result Elements are collected by maxBy into an Optional of Employee. The finisher Optional::get unwraps it, and the final result is a plain Employee. In a groupingBy, this happens once per group. elementsone group INPUT maxByby salary Optionalof Employee finisherOptional::get Employeefinal result RESULT COLLECT, THEN FINISH
Figure 1: The downstream collector produces its usual result; the finisher converts it once, at the end.

3. Java Examples

Example 1: Making a collected list unmodifiable

Return an unmodifiable list of approved loan ids from a service method that must run on Java 8.

UnmodifiableResult.java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class UnmodifiableResult {

    public static void main(String[] args) {
        List<String> approved = Arrays.asList("L-101", "L-205", "L-310").stream()
                .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));

        try {
            approved.add("L-999");
        } catch (UnsupportedOperationException e) {
            System.out.println("Read-only list: " + approved);
        }
    }
}
Output
Read-only list: [L-101, L-205, L-310]

How it works: This was the standard way to get an unmodifiable result before toUnmodifiableList() (Java 10) and Stream.toList() (Java 16).

Example 2: Unwrapping Optional per group (Java 16+)

Find the top earner in each department as a plain object, not an Optional.

TopEarnerPerDept.java
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;

public class TopEarnerPerDept {

    record Employee(String name, String dept, int salary) { }

    public static void main(String[] args) {
        List<Employee> staff = List.of(
                new Employee("Asha", "Eng", 95_000), new Employee("Bo", "Eng", 120_000),
                new Employee("Cleo", "Ops", 64_000), new Employee("Dev", "Ops", 58_000));

        Map<String, String> topEarner = staff.stream()
                .collect(Collectors.groupingBy(Employee::dept, TreeMap::new,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparingInt(Employee::salary)),
                                best -> best.map(Employee::name).orElse("-"))));

        System.out.println(topEarner);
    }
}
Output
{Eng=Bo, Ops=Cleo}

How it works: maxBy() returns an Optional per group. The finisher turns it into the employee's name. Groups created by groupingBy() always have at least one element, so Optional::get would also be safe here.

Example 3: Turning a collection into a derived value (Java 16+)

For each course, report how many distinct students enrolled, even if some enrolled twice.

DistinctStudentsPerCourse.java
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class DistinctStudentsPerCourse {

    record Enrolment(String course, String student) { }

    public static void main(String[] args) {
        List<Enrolment> enrolments = List.of(
                new Enrolment("Java", "s1"), new Enrolment("Java", "s2"), new Enrolment("Java", "s1"),
                new Enrolment("SQL", "s3"));

        Map<String, Integer> distinctCount = enrolments.stream()
                .collect(Collectors.groupingBy(Enrolment::course, TreeMap::new,
                        Collectors.collectingAndThen(
                                Collectors.mapping(Enrolment::student, Collectors.toSet()),
                                Set::size)));

        System.out.println(distinctCount);
    }
}
Output
{Java=2, SQL=1}

How it works: The downstream collector builds a set of student ids per course, and the finisher Set::size keeps only its size.

Example 4: Formatting the final value (Java 16+)

Compute the average rating per product and round it to one decimal place as a display string.

RoundedRatings.java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class RoundedRatings {

    record Review(String product, int stars) { }

    public static void main(String[] args) {
        List<Review> reviews = List.of(
                new Review("Kettle", 5), new Review("Kettle", 4), new Review("Kettle", 4), new Review("Iron", 3));

        Map<String, String> ratings = reviews.stream()
                .collect(Collectors.groupingBy(Review::product, TreeMap::new,
                        Collectors.collectingAndThen(Collectors.averagingInt(Review::stars),
                                avg -> String.format("%.1f stars", avg))));

        System.out.println(ratings);
    }
}
Output
{Iron=3.0 stars, Kettle=4.3 stars}

How it works: The finisher formats each group's average once, after it is computed, so the map is ready for display.

4. Real-World Use Cases

  • Unwrapping optionals from maxBy() and minBy() per group.
  • Read-only results on Java 8 code bases.
  • Derived values: sizes, rounded numbers or formatted strings per group.
  • Wrapping results in domain objects, such as a Report built from a collected list.

5. Important Points

  • Runs once per result, not per element.
  • Finisher exceptions propagate from the terminal operation.
  • Unmodifiable views: Collections.unmodifiableList() wraps the list; on Java 10+, toUnmodifiableList() is shorter.
  • Type inference can struggle with long nested collectors; extract a variable or add type hints.
  • Parallel safe: the finisher runs after combining.

6. With and Without collectingAndThen()

NeedWithout collectingAndThen()With collectingAndThen()
Read-only list (Java 8)Wrap the result afterwardscollectingAndThen(toList(), Collections::unmodifiableList)
Max per group without OptionalPost-process the mapcollectingAndThen(maxBy(c), Optional::get)
Size of distinct values per groupSecond pass over the mapcollectingAndThen(toSet(), Set::size)
Read-only list (Java 10+)toUnmodifiableList()Not needed

7. Common Mistakes and Best Practices

Using it for per-element work

The finisher sees the final collected value only. To change each element, use map() or mapping().

Calling Optional.get() blindly at the top level

Risky
Employee top = staff.stream().collect(collectingAndThen(maxBy(bySalary), Optional::get));   // fails if staff is empty

Inside groupingBy() groups are never empty, but at the top level the stream may be. Use orElseThrow() with a clear message or a default.

Other mistakes to avoid

  • Deep nesting of several adapters on one line; extract named collectors.
  • Using it where a simpler collector exists, such as toUnmodifiableList() on Java 10+.
  • Expecting the finisher to run for an empty top-level stream with Optional::get; it throws.

8. Summary

  • collectingAndThen() applies a finishing function to a collector's result.
  • It is most useful per group: unwrapping Optional, computing sizes, formatting values.
  • The finisher runs once per result, not per element.
  • On Java 10+, prefer toUnmodifiableList() for read-only lists.

9. References