Course contentsShow
← Java
Lesson 1612 of 2,87034. Collectors in DepthFree lesson

teeing with Complex Collectors: groupingBy and toList

Using teeing with sophisticated downstream collectors to produce multiple groupings or collections simultaneously.

teeing with Complex Collectors: groupingBy and toList

What You'll Learn

You'll discover how to use Collectors.teeing() with sophisticated collectors like groupingBy() and toList() to perform multiple complex aggregations in a single stream pass.

Beyond Simple Aggregations

Until now, you've seen teeing() combine simple collectors like counting() or summingInt(). But teeing() truly shines when you pair it with complex downstream collectors. You can simultaneously group elements and collect them into a list, all without traversing your data twice.

The Power Pattern

Imagine you need both a grouped breakdown of data and a complete list of all items. Without teeing(), you'd either process the stream twice or collect once and derive the second result manually. With teeing(), you declare both intentions upfront:

record Result(Map<Category, List<Product>> grouped, List<Product> all) {}

Result result = products.stream()
    .collect(Collectors.teeing(
        Collectors.groupingBy(Product::category),
        Collectors.toList(),
        (grouped, all) -> new Result(grouped, all)
    ));

The first collector (groupingBy) organizes products by category into a map. The second collector (toList) captures every product in order. The merger function packages both into your custom Result object.

Real-World Scenario

Think of analyzing sales data: you might need products grouped by region for regional reports, but also a master list sorted chronologically. Both collectors operate simultaneously as elements flow through, with the merger combining their independent results at the end.

You can even nest further: use groupingBy with its own downstream collector as one half of teeing(), creating multi-dimensional views of your data in one elegant operation.

Key Takeaway:
teeing() with complex collectors like groupingBy() and toList() enables sophisticated multi-dimensional data collection in a single pass, combining structural organization with complete data capture efficiently.