Collectors.teeing() in Java
Collectors.teeing() is a static method added to java.util.stream.Collectors in Java 12. It sends every element of a stream to two downstream collectors at the same time, then combines their two results with a merger function. The name comes from a T-shaped pipe fitting that splits one flow into two.
It solves a common problem: computing two different aggregates, such as a count and a sum, or a minimum and a maximum, in a single pass over a stream that can only be consumed once. This tutorial covers its signature, typical combinations and its limits.
1. Syntax and Method Signature
// java.util.stream.Collectors (Java 12)
static <T, R1, R2, R> Collector<T, ?, R> teeing(
Collector<? super T, ?, R1> downstream1,
Collector<? super T, ?, R2> downstream2,
BiFunction<? super R1, ? super R2, R> merger)
Each element goes to both downstream1 and downstream2. When the stream ends, the merger receives their results R1 and R2 and returns the final result R, often a record.
record Range(int min, int max) { }
Range range = prices.stream().collect(Collectors.teeing(
Collectors.minBy(Integer::compare), Collectors.maxBy(Integer::compare),
(min, max) -> new Range(min.orElse(0), max.orElse(0))));
2. How teeing() Works
teeing() builds a composite collector. Its container holds the containers of both downstream collectors; its accumulator passes each element to both; its combiner merges both pairs of partial results for parallel streams; and its finisher finishes both and calls the merger.
Because the stream is read only once, teeing() works on streams that cannot be recreated, such as lines read from a network source, and avoids iterating a large collection twice.
3. Java Examples
Example 1: Count and sum in one pass (Java 12+)
Compute the average order value from a stream of order amounts, reading the data only once.
import java.util.List;
import java.util.stream.Collectors;
public class AverageOrderValue {
public static void main(String[] args) {
List<Integer> amounts = List.of(1200, 450, 3300);
double average = amounts.stream()
.collect(Collectors.teeing(
Collectors.counting(),
Collectors.summingInt(Integer::intValue),
(count, sum) -> count == 0 ? 0.0 : (double) sum / count));
System.out.println("Average order value: " + average);
}
}
Average order value: 1650.0
How it works: The two collectors run side by side, and the merger divides the sum by the count. averagingInt() exists for this exact case, but the pattern extends to any pair of collectors.
Example 2: Minimum and maximum as a record (Java 16+)
Find the cheapest and most expensive hotel prices for a search result header.
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class PriceRange {
record Hotel(String name, int price) { }
record Range(String cheapest, String priciest) { }
public static void main(String[] args) {
List<Hotel> hotels = List.of(
new Hotel("Lake View", 4200), new Hotel("City Inn", 2900), new Hotel("Palm Court", 7800));
Range range = hotels.stream()
.collect(Collectors.teeing(
Collectors.minBy(Comparator.comparingInt(Hotel::price)),
Collectors.maxBy(Comparator.comparingInt(Hotel::price)),
(min, max) -> new Range(
min.map(h -> h.name() + " " + h.price()).orElse("-"),
max.map(h -> h.name() + " " + h.price()).orElse("-"))));
System.out.println(range);
}
}
Range[cheapest=City Inn 2900, priciest=Palm Court 7800]
How it works: A record makes a clear result type for the two values. minBy() and maxBy() return optionals, which the merger unwraps safely.
Example 3: Two filtered lists in one pass (Java 16+)
Split log lines into errors and warnings and report both counts with the first error.
import java.util.List;
import java.util.stream.Collectors;
public class ErrorsAndWarnings {
record Summary(List<String> errors, long warnings) { }
public static void main(String[] args) {
List<String> log = List.of("INFO start", "WARN slow disk", "ERROR db down", "WARN retry", "ERROR timeout");
Summary summary = log.stream()
.collect(Collectors.teeing(
Collectors.filtering(l -> l.startsWith("ERROR"), Collectors.toList()),
Collectors.filtering(l -> l.startsWith("WARN"), Collectors.counting()),
Summary::new));
System.out.println("Errors: " + summary.errors());
System.out.println("Warnings: " + summary.warnings());
}
}
Errors: [ERROR db down, ERROR timeout] Warnings: 2
How it works: Each branch filters with filtering() (Java 9) before collecting. The record's constructor reference Summary::new is a valid merger because it takes the two results in order.
Example 4: Nesting teeing() for more than two results (Java 16+)
Compute count, total and maximum of transaction amounts with nested teeing().
import java.util.List;
import java.util.stream.Collectors;
public class ThreeStats {
record Stats(long count, int total, int max) { }
public static void main(String[] args) {
List<Integer> txns = List.of(500, 1250, 300, 980);
Stats stats = txns.stream()
.collect(Collectors.teeing(
Collectors.counting(),
Collectors.teeing(
Collectors.summingInt(Integer::intValue),
Collectors.maxBy(Integer::compare),
(sum, max) -> new int[]{sum, max.orElse(0)}),
(count, sumMax) -> new Stats(count, sumMax[0], sumMax[1])));
System.out.println(stats);
}
}
Stats[count=4, total=3030, max=1250]
How it works: Nesting works, but it quickly becomes hard to read. For count, sum, min, max and average, summarizingInt() is simpler; keep teeing() for genuinely different pairs of collectors.
4. Real-World Use Cases
- Dashboards: total and count, or best and worst value, in one pass.
- Validation summaries: list of invalid records plus the number of valid ones.
- Streams that cannot be repeated: data read once from a file, socket or queue.
- Ratios: share of failed payments as failed count divided by total count.
5. Important Points
- Java 12 or later is required.
- Exactly two downstream collectors; nest for more, sparingly.
- Empty streams: both collectors see nothing; the merger must handle their empty results, such as 0 or empty optionals.
- Parallel safe if both downstream collectors are.
- Use a record as the merger's result type for readable code.
6. teeing() vs Other Approaches
| Need | Best tool | Since |
|---|---|---|
| Two different aggregates, one pass | teeing() | Java 12 |
| Count, sum, min, max, average | summarizingInt() | Java 8 |
| Average only | averagingInt() | Java 8 |
| Two passes acceptable, collection available | Two separate pipelines | Java 8 |
See Java 12 teeing Collector for its place among the Java 12 changes.
7. Common Mistakes and Best Practices
Streaming a collection twice when one pass is possible
long count = orders.stream().filter(Order::paid).count();
int total = orders.stream().filter(Order::paid).mapToInt(Order::amount).sum(); // two passes
var result = orders.stream().filter(Order::paid).collect(Collectors.teeing(
Collectors.counting(), Collectors.summingInt(Order::amount), PaidSummary::new));
Ignoring the empty case in the merger
Dividing a sum by a count of 0 or calling get() on an empty Optional fails for empty streams. Example 1 guards the division explicitly.
Other mistakes to avoid
- Using
teeing()wheresummarizingInt()already gives everything. - Deeply nested teeing that nobody can read.
- Using it on Java 8 to 11. It does not exist there.
8. Summary
teeing()(Java 12) sends every element to two collectors and merges their results.- It computes two aggregates in a single pass over a stream.
- Use a record as the result type, and handle empty results in the merger.
- Prefer
summarizingInt()when it already covers the statistics you need.
9. References
Frequently Asked Questions (FAQ)
Q1. What does Collectors.teeing() do?
teeing(), added in Java 12, passes every element to two downstream collectors at the same time and combines their results with a merger function, so two aggregates are computed in a single pass.
Q2. Why is it called teeing?
It is named after a T-shaped pipe fitting, a tee, which splits one flow into two branches, just as the collector splits the stream into two collectors.
Q3. Can teeing() combine more than two collectors?
Not directly. You can nest teeing() inside teeing(), but for many statistics a single collector such as summarizingInt() or a custom collector is clearer.
Q4. What Java version introduced Collectors.teeing()?
Java 12. On older versions, use two pipelines over a collection or write a custom collector.
Q5. What happens with an empty stream?
Both downstream collectors produce their empty results, for example 0 from counting() or an empty Optional from maxBy(), and the merger receives those. Write the merger so it handles them.