What is Collectors.teeing and Why It Exists
You'll learn what the teeing collector does and why Java provides it for dual-stream processing.
The Core Idea
Collectors.teeing() lets you process the same stream with two different collectors simultaneously and then combine their results into a single output. Instead of collecting a stream twice (which you can't do—streams are consumed after a terminal operation), teeing applies two collectors in parallel and merges their results using a function you provide.
Think of it like splitting a river into two channels that flow through different mills, then combining what both mills produce into one final product.
Why It Exists
Before teeing (introduced in Java 12), if you needed two different aggregations from the same stream, you had awkward choices:
- Collect to a temporary collection, then stream it twice (inefficient)
- Manually track two values in a custom collector (complex)
- Use two separate streams (wastes resources)
teeing solves this elegantly by letting you declare: "I want both of these results, combined this way."
The Signature
Collectors.teeing(
Collector<T, ?, R1> downstream1,
Collector<T, ?, R2> downstream2,
BiFunction<R1, R2, R> merger
)
It takes two collectors, runs both on the stream, and passes both results to your merger function.
Common Use Cases
- Calculate both average and maximum from numeric data
- Find both the shortest and longest string
- Get both a count and a sum simultaneously
- Extract both unique elements and total count
Key Takeaway: Collectors.teeing() enables efficient dual-processing of a stream, applying two collectors simultaneously and combining their results with a merge function—avoiding the need to traverse data twice.