00:00

Collectors.teeing() in Java

Last updated:

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

Collectors.java (API)
// 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.

Usage
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.

teeing() feeds every element to two collectors and merges the results Order amounts 1200, 450 and 3300 flow into two collectors at once. counting produces 3. summingInt produces 4950. The merger combines them into an average order value of 1650. ELEMENTS COLLECTOR RESULT Branch 1 1200, 450, 3300 counting() 3 Branch 2 1200, 450, 3300 summingInt() 4950 Merger (n, sum) -> sum / n 1650
Figure 1: Both collectors see every element in the same pass. The merger turns their two results into one value.

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.

AverageOrderValue.java
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);
    }
}
Output
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.

PriceRange.java
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);
    }
}
Output
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.

ErrorsAndWarnings.java
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());
    }
}
Output
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().

ThreeStats.java
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);
    }
}
Output
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

NeedBest toolSince
Two different aggregates, one passteeing()Java 12
Count, sum, min, max, averagesummarizingInt()Java 8
Average onlyaveragingInt()Java 8
Two passes acceptable, collection availableTwo separate pipelinesJava 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

Two passes
long count = orders.stream().filter(Order::paid).count();
int total = orders.stream().filter(Order::paid).mapToInt(Order::amount).sum();   // two passes
One pass
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() where summarizingInt() 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