The collect Method and the Collector Interface
What you'll learn: How collect provides a flexible way to accumulate stream elements into containers using the Collector interface.
Understanding collect as a Reduction Operation
You've already seen reduce for folding streams into single values. The collect method is a more sophisticated reduction operation designed specifically for accumulating elements into mutable containers like lists, sets, or maps.
Think of reduce as combining values directly (like adding numbers), while collect is like filling different types of containers. Instead of building the result step-by-step from scratch, collect creates a container once and then keeps adding elements to it—a much more efficient pattern for collections.
The Collector Interface
The Collector interface encapsulates the logic for:
- Creating an empty result container
- Adding elements to that container
- Combining multiple containers (for parallel streams)
- Optionally transforming the final result
You don't typically implement Collector yourself. Java provides pre-built collectors in the Collectors utility class (which you'll learn about next), but understanding that collect uses a Collector helps you grasp what's happening under the hood.
Basic collect Syntax
<R, A> R collect(Collector<? super T, A, R> collector)
The method signature looks complex, but in practice it's simple: pass a Collector that knows how to build your desired result type.
Why collect Instead of reduce?
While you could use the three-argument reduce for collections, collect is purpose-built for this task. It's more readable, handles parallelism better, and makes your intent crystal clear: you're gathering elements into a container, not performing a mathematical fold.
Key Takeaway: The collect method is a specialized reduction operation that uses a Collector to efficiently accumulate stream elements into mutable result containers like lists, sets, and maps.