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

The Merger BiFunction: Combining Two Results

Understanding how the merger BiFunction receives results from both collectors and produces the final output.

The Merger BiFunction: Combining Two Results

You'll learn how the merger function in Collectors.teeing() combines the outputs of two separate collectors into a single result.

Understanding the Merger's Role

When you use Collectors.teeing(), two independent collectors process your stream simultaneously. Each produces its own result. But you don't want two separate values — you want one cohesive answer. That's where the merger BiFunction comes in.

Think of it like a recipe that calls for two separate preparations: one chef makes the sauce, another makes the pasta. The merger is the final plating step where both components are combined into one dish.

The BiFunction Signature

The merger is a BiFunction<R1, R2, R> where:

  • R1 is the result type from the first collector
  • R2 is the result type from the second collector
  • R is your final, combined result type

How It Works in Practice

List<Integer> numbers = List.of(10, 20, 30, 40);

String result = numbers.stream()
    .collect(Collectors.teeing(
        Collectors.summingInt(Integer::intValue),  // First collector → Integer
        Collectors.counting(),                      // Second collector → Long
        (sum, count) -> "Sum: " + sum + ", Count: " + count  // Merger
    ));
// Result: "Sum: 100, Count: 4"

The merger receives 100 (the sum) and 4 (the count) as parameters, then decides what to do with them — in this case, formatting them into a descriptive string.

You Control the Output

The merger gives you complete freedom. You can create custom objects, perform calculations, build formatted strings, or return any type that makes sense for your use case.

Key Takeaway: The merger BiFunction is teeing's final step, receiving both collectors' results as parameters and combining them into whatever single output you need.