Skip to main content
Java 12 · Topic 1 of 2

Collectors.teeing

Definition​

Collectors.teeing (Java 12) runs two collectors over the same stream at once and combines their two results. It saves you from going through the data twice.

Example code​

Count and total in one pass, then compute the average

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

class Demo {
public static void main(String[] args) {
List<Integer> marks = List.of(70, 80, 90, 100);

double average = marks.stream().collect(Collectors.teeing(
Collectors.counting(), // first result: how many
Collectors.summingInt(Integer::intValue), // second result: the total
(count, total) -> (double) total / count)); // combine them

System.out.println(average);
}
}

// Output:
// 85.0

Finished this page? Track your progress (saved only in your browser).