Collectors.teeing() in Stream API Example

1. Introduction

This blog post explores Collectors.teeing(), an addition to the Java Stream API introduced in Java 12. This collector is particularly useful for performing two different collecting operations in a single pass over the data and then merging their results.

Definition

Collectors.teeing() is a method in the Java Stream API that combines two collectors. It processes elements through two different collectors, then merges their results with a BiFunction. This is useful for scenarios where you need to perform distinct operations on the same stream without iterating over the data multiple times.

2. Program Steps

1. Create a stream of data.

2. Apply Collectors.teeing() to perform two separate operations on the stream.

3. Merge the results of these operations.

3. Code Program

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectorsTeeingExample {
    public static void main(String[] args) {
        var numbers = Stream.of(1, 2, 3, 4, 5);

        // Using Collectors.teeing() to get the sum and count of elements
        var result = numbers.collect(
            Collectors.teeing(
                Collectors.summingInt(Integer::intValue), // First collector
                Collectors.counting(), // Second collector
                (sum, count) -> "Sum: " + sum + ", Count: " + count // Merging results
            )
        );

        System.out.println(result);
    }
}

Output:

Sum: 15, Count: 5

Explanation:

1. A stream of integers (numbers) is created.

2. Collectors.teeing() is used to combine two collectors: Collectors.summingInt() and Collectors.counting().

3. The first collector calculates the sum of the integers, and the second collector counts the number of elements in the stream.

4. The results of these two collectors are then merged into a string that displays both the sum and the count.

5. The output shows the combined result of these operations, demonstrating the effectiveness of Collectors.teeing() in simultaneously performing and merging different operations on a stream.


Comments