Video in progress

When and how do you write your own Collector?

When combinations of the ready-made collectors aren't enough, or when the same collecting logic is repeated in many places. The easiest way is Collector.of(supplier, accumulator, combiner, finisher): create a container, add an element, merge two containers and produce the final result.

📖 Answer

Example: building a "count, total amount, largest amount" report from orders in a single pass.

final class OrderStats {
    long count;
    long total;
    long max = Long.MIN_VALUE;

    void add(Order o) {
        count++;
        total += o.amount();
        max = Math.max(max, o.amount());
    }

    OrderStats merge(OrderStats other) {
        count += other.count;
        total += other.total;
        max = Math.max(max, other.max);
        return this;
    }
}

record Report(long count, long total, long max) {}

static Collector<Order, OrderStats, Report> toReport() {
    return Collector.of(
            OrderStats::new,                 // supplier
            OrderStats::add,                 // accumulator
            OrderStats::merge,               // combiner, for parallel
            s -> new Report(s.count, s.total, s.count == 0 ? 0 : s.max));
}

Report r = orders.stream().collect(toReport());
Map<String, Report> byCity = orders.stream().collect(groupingBy(Order::city, toReport()));

The last line shows that your own collector also works as a downstream inside groupingBy, which is the biggest benefit.

Don't skip the combiner on the grounds that "we don't use parallel". It has to be correct, otherwise when someone calls parallelStream() the result is silently wrong.

In most cases you don't need your own collector: collectingAndThen, teeing and reducing get you there. So try the ready-made ones first.