Stream Smarter with Java 12 Teeing Collectors

~
~
Published on
Authors
java-12-teeing-collectors-banner

Stream Smarter with Java 12 Teeing Collectors

Java 12 introduced several features, but there is one thats stands out for me, it is a small library enhancement tracked in the JDK bug system (JDK-8209685 / JDK-8205461): Teeing Collectors. Let’s dive into what they are, why they matter, and how to use them effectively.

What Is a Teeing Collector?

The Collectors.teeing() method allows you to combine two collectors and merge their results using a custom function.

Syntax

Collectors.teeing(collector1, collector2, mergerFunction)

Why Use Teeing Collectors?

  • Eliminate multiple stream passes
  • Simplify complex aggregation
  • Write cleaner, more maintainable code

Example: Calculating Average and Count in One Pass

Without Teeing (Two Stream Passes)

long count = list.stream().count();
double average = list.stream().mapToInt(Integer::intValue).average().orElse(0);
With Teeing (One Stream Pass)
var result = list.stream().collect(
    Collectors.teeing(
        Collectors.counting(),
        Collectors.averagingInt(Integer::intValue),
        (count, avg) -> Map.of("count", count, "average", avg)
    )
);

Real-World Use Cases

  • Summarizing sales data
  • Processing user metrics
  • Combining multiple statistics

Final Thoughts

If you're using Java 12 or later, Teeing Collectors offer a performance-friendly and clean way to handle complex data processing. Give it a shot and make your streams even more powerful.