Java 12: Collectors.teeing merges two collectors

teeing feeds each element to two collectors and combines their results.

Code
record Stats(long count, int sum) {}
List<Integer> nums = List.of(2, 4, 6, 8);
Stats s = nums.stream().collect(Collectors.teeing(
        Collectors.counting(),
        Collectors.summingInt(Integer::intValue),
        (count, sum) -> new Stats(count, sum)));
System.out.println(s);
Output
Stats[count=4, sum=20]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26