Course contentsShow
← Java
Lesson 1608 of 2,87034. Collectors in DepthFree lesson

The teeing Method Signature and Type Parameters

Exploring teeing's signature: two downstream collectors, a merger BiFunction, and how types flow through the operation.

The teeing Method Signature and Type Parameters

You'll learn: How Collectors.teeing() is structured with two downstream collectors, a merger function, and how Java infers the types flowing through this sophisticated operation.

Understanding the Signature

The teeing collector has a precise, type-safe signature that coordinates three components:

public 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
)

Let's break down these type parameters:

The Type Parameters Explained

T — The type of elements flowing into both downstream collectors. This is what your stream produces.

R1 — The result type of the first downstream collector. For example, if you use counting(), this would be Long.

R2 — The result type of the second downstream collector. It can be completely different from R1.

R — The final result type after the merger function combines R1 and R2.

How Types Flow

Think of teeing as a Y-shaped pipeline: the stream of type T splits and flows into two separate collectors. The first produces an R1, the second produces an R2. These two results meet at the merger BiFunction<R1, R2, R>, which combines them into your final result R.

Example type flow:

  • Stream of Integer (T = Integer)
  • First collector: summingInt() produces Integer (R1 = Integer)
  • Second collector: counting() produces Long (R2 = Long)
  • Merger: combines Integer and Long into, say, Double (R = Double)

Key Takeaway: The teeing signature uses four type parameters to safely orchestrate splitting one stream into two collectors and merging their distinct result types into a single final output.