Teeing collector in Java 12

In Java 12, a new collector called “teeing collector” was introduced. This collector allows you to perform two separate operations on the elements of a stream and then combine the results in a desired way. The teeing collector is useful when you want to perform multiple computations simultaneously on a stream without having to iterate over it multiple times.

How it works

The teeing collector takes three parameters:

Here is the general syntax for using the teeing collector:

Collector<T, ?, R1> collector1 = ...;
Collector<T, ?, R2> collector2 = ...;

BiFunction<R1, R2, R> combiner = ...;

R result = Stream
    .collect(Collectors.teeing(collector1, collector2, combiner));

Example

Let’s say we have a list of integers and we want to find the sum and average of these numbers using the teeing collector.

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

public class TeetingCollectorExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        Collector<Integer, ?, Integer> sumCollector = Collectors.summingInt(Integer::intValue);
        Collector<Integer, ?, Double> averageCollector = Collectors.averagingInt(Integer::intValue);

        Integer sum = numbers.stream()
                .collect(Collectors.teeing(sumCollector, averageCollector, Integer::sum));

        Double average = numbers.stream()
                .collect(Collectors.teeing(sumCollector, averageCollector, (s, a) -> a));

        System.out.println("Sum: " + sum);
        System.out.println("Average: " + average);
    }
}

In this example, we create two collectors - sumCollector and averageCollector - to compute the sum and average of the numbers, respectively. We then use the teeing collector to combine the results of these collectors and obtain the sum and average.

The output of this program will be:

Sum: 55
Average: 5.5

Conclusion

The teeing collector in Java 12 is a useful addition to the Java Stream API. It allows you to perform multiple computations on a stream in a single pass, improving efficiency and reducing code complexity. By combining the results of separate collectors, you can easily perform complex operations on stream elements.