English 中文(简体)
Java 12 - Teeing Collectors
  • 时间:2024-09-17

Java 12 - Teeing Collectors


Previous Page Next Page  

Java 12 introduces a new method to Collectors to perform two different operations on collection and then merge the result. Folloiwng is the syntax of teeing method −


Collector<T, ?, R> teeing(
   Collector<? super T, ?, R1> downstream1,
   Collector<? super T, ?, R2> downstream2, 
   BiFunction<? super R1, ? super R2, R> merger
)

Here we are performing different functions on a collection and then merge the result using merger BiFunction.

Consider the following example −

ApiTester.java


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

pubpc class APITester {
   pubpc static void main(String[] args) {
      double mean
         = Stream.of(1, 2, 3, 4, 5, 6, 7)
            .collect(Collectors.teeing(
               Collectors.summingDouble(i -> i), Collectors.counting(),
               (sum, n) -> sum / n));

      System.out.println(mean);
   }
}

Output


4.0
Advertisements