teeing and Summary Statistics
Get two answers from a single pass with teeing, plus full number summaries.
Open this lesson in the learning hubKey points
Collectors.teeing(Java 12+) runs two collectors over the same stream in one pass, then merges their results.- Use it when you need two answers at once: count and sum, min and max, matched and total.
- Without teeing you would stream twice, which is impossible when the source is one-shot.
summarizingIntreturns count, sum, min, max and average in a single object.averagingIntreturns a Double and gives 0.0 for an empty stream, not an Optional.
Example
import java.util.*;
import java.util.stream.*;
public class Main {
record Report(long count, int total, double average) {}
public static void main(String[] args) {
List<Integer> orders = List.of(20, 35, 15, 60, 10);
// teeing (Java 12+) runs two collectors in ONE pass, then merges the answers.
Report report = orders.stream().collect(Collectors.teeing(
Collectors.counting(),
Collectors.summingInt(Integer::intValue),
(count, total) -> new Report(count, total, count == 0 ? 0 : (double) total / count)));
// summarizingInt gets count, sum, min, max and average in one shot.
IntSummaryStatistics stats = orders.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
String range = orders.stream().collect(Collectors.teeing(
Collectors.minBy(Comparator.<Integer>naturalOrder()),
Collectors.maxBy(Comparator.<Integer>naturalOrder()),
(min, max) -> min.orElse(0) + ".." + max.orElse(0)));
System.out.println("teeing : " + report);
System.out.println("stats : " + stats);
System.out.println("average : " + orders.stream().collect(Collectors.averagingInt(Integer::intValue)));
System.out.println("range : " + range);
}
}
One pass, two answers. That is teeing.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Streams course, and every lesson in it is listed on the Streams contents page.