Summary statistics and teeing
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Collectors.summarizingInt reads a stream once and returns an IntSummaryStatistics object that holds five answers together: the count, sum, minimum, average and maximum. Collectors.teeing sends every element to two collectors at once and joins their two results into one.
Five answers in one pass
A class marks report needs the number of students, the total, the lowest, the highest and the average. Asking five separate questions means five passes over the data: count(), a sum, min, max and an average.
Example 1 · Five variables in a loop versus summarizingInt
import java.util.IntSummaryStatistics;import java.util.List;import java.util.stream.Collectors;
public class MarksStatsDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 91, 58, 66, 84);
// old way: one loop, five variables int count = 0; int sum = 0; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int m : marks) { count++; sum += m; min = Math.min(min, m); max = Math.max(max, m); } System.out.println("Loop: count " + count + ", sum " + sum + ", min " + min + ", max " + max + ", average " + (double) sum / count);
// new way: one collector IntSummaryStatistics stats = marks.stream() .collect(Collectors.summarizingInt(m -> m)); System.out.println("Count: " + stats.getCount()); System.out.println("Sum: " + stats.getSum()); System.out.println("Min: " + stats.getMin()); System.out.println("Max: " + stats.getMax()); System.out.println("Average: " + stats.getAverage()); System.out.println(stats); }}Loop: count 5, sum 371, min 58, max 91, average 74.2
Count: 5
Sum: 371
Min: 58
Max: 91
Average: 74.2
IntSummaryStatistics{count=5, sum=371, min=58, average=74.200000, max=91}What this code does
- Both versions read the marks once.
summarizingInt(m -> m)keeps the five running values for you, so there is nothing to set up and no chance of forgetting the(double)cast for the average. toString()shows all five values at once, which is handy while debugging. In a report, use the getters and format the average yourself.- Why summarizingInt: five variables in a loop can be updated wrongly or left out of a single place. One collector keeps all five in step with each other.
The old loop way did it in one pass, but with five variables to set up and update by hand.
summarizingInt(Student::marks) does the one-pass loop for you. It takes a function that turns each element into an int, and returns an IntSummaryStatistics, a small object that kept all five values while the stream went by. For decimal values such as CGPA or petrol prices, use summarizingDouble, which returns a DoubleSummaryStatistics. summarizingLong exists too.
Reading IntSummaryStatistics
The statistics object has one getter per answer. Note the types: the count and sum are long, because they can grow past the int limit.
Example 2 · Trap: statistics of an empty stream
import java.util.IntSummaryStatistics;import java.util.List;import java.util.stream.Collectors;
record Student(String name, String branch, int marks) {}
public class EmptyStatsDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Asha", "CSE", 88), new Student("Ravi", "ECE", 72));
IntSummaryStatistics mech = students.stream() .filter(s -> s.branch().equals("MECH")) .collect(Collectors.summarizingInt(Student::marks)); System.out.println("Count: " + mech.getCount() + ", average: " + mech.getAverage()); System.out.println("Min: " + mech.getMin() + ", max: " + mech.getMax());
if (mech.getCount() == 0) { System.out.println("MECH: no students yet"); } else { System.out.println("MECH highest: " + mech.getMax()); } }}Count: 0, average: 0.0 Min: 2147483647, max: -2147483648 MECH: no students yet
What this code does
- No student is in MECH, so the stream is empty. The count and average are 0, which looks fine, but the minimum and maximum are the starting values
Integer.MAX_VALUEandInteger.MIN_VALUE. - A report that printed "highest marks: -2147483648" would confuse everyone. Check
getCount()first and show a clear message for an empty group.
Example 3 · Statistics per branch with groupingBy
import java.util.DoubleSummaryStatistics;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, double cgpa) {}
public class BranchCgpaDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Asha", "CSE", 8.6), new Student("Ravi", "ECE", 7.4), new Student("Neha", "CSE", 9.1), new Student("Kiran", "ECE", 8.0), new Student("Divya", "CSE", 7.9), new Student("Imran", "MECH", 6.8));
Map<String, DoubleSummaryStatistics> byBranch = students.stream() .collect(Collectors.groupingBy(Student::branch, Collectors.summarizingDouble(Student::cgpa)));
System.out.println("Branch Count Min Max Average"); new TreeMap<>(byBranch).forEach((b, s) -> System.out.printf("%-6s %5d %.1f %.1f %.2f%n", b, s.getCount(), s.getMin(), s.getMax(), s.getAverage())); }}Branch Count Min Max Average CSE 3 7.9 9.1 8.53 ECE 2 7.4 8.0 7.70 MECH 1 6.8 6.8 6.80
What this code does
summarizingDoubleas the downstream collector gives oneDoubleSummaryStatisticsper branch, so the table needs onecollectcall instead of four maps.- Every group from
groupingByhas at least one student, so min and max are always real values here.printfkeeps the decimals short.
getCount()(long) andgetSum()(long for int input, double for double input).getMin()andgetMax()(int forIntSummaryStatistics).getAverage()(double), already worked out with a decimal part.- Empty stream trap: count is 0, average is 0.0, but
getMin()isInteger.MAX_VALUE(2147483647) andgetMax()isInteger.MIN_VALUE. CheckgetCount() > 0before showing them.
summarizingInt also works as a downstream collector: groupingBy(Student::branch, summarizingInt(Student::marks)) gives full statistics for every branch.teeing: two collectors, one result
Sometimes you need two different collectors over the same data, such as the pass count and the total count to work out a pass percentage. Collectors.teeing(first, second, merger) (Java 12) sends every element to both collectors.
Example 4 · teeing: pass percentage and marks range
import java.util.List;import java.util.stream.Collectors;
public class TeeingDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 35, 91, 58, 28, 66, 84, 40);
double passPercent = marks.stream() .collect(Collectors.teeing( Collectors.summingInt(m -> m >= 40 ? 1 : 0), // passed students Collectors.counting(), // all students (passed, total) -> passed * 100.0 / total)); System.out.println("Pass percentage: " + passPercent);
String range = marks.stream() .collect(Collectors.teeing( Collectors.minBy(Integer::compare), Collectors.maxBy(Integer::compare), (low, high) -> "from " + low.get() + " to " + high.get())); System.out.println("Marks range " + range); }}Pass percentage: 75.0 Marks range from 28 to 91
What this code does
- The first
teeingsends every mark to two collectors: one adds 1 for each pass, the other counts everyone. The merger receivespassed = 6andtotal = 8and returns 75.0. - The second joins
minByandmaxByinto one sentence. Both results areOptional<Integer>; the list is not empty, soget()is safe. Withoutteeing, each answer would need its own pass.
When the stream ends, it calls merger with the two results and returns what the merger builds. The name comes from a T-shaped pipe joint: one stream flows in and splits into two branches, and the merger joins them at the end. The merger is a function of two arguments, so it can return a number, a string or a record that holds both results.
Use teeing when the two answers come from different collectors, for example a summingInt and a counting, or a minBy and a maxBy.
Real-world use: a marks summary card
A class teacher's summary card shows the class size, the average, the highest and lowest marks, the topper's name and the pass percentage. summarizingInt covers the numbers in one pass.
Example 5 · Real world: the class summary card
import java.util.Comparator;import java.util.IntSummaryStatistics;import java.util.List;import java.util.Optional;import java.util.stream.Collectors;
record Student(String name, int marks) {}
record Card(IntSummaryStatistics stats, String topper) {}
public class SummaryCardDemo { public static void main(String[] args) { List<Student> classA = List.of( new Student("Asha", 88), new Student("Ravi", 34), new Student("Neha", 93), new Student("Imran", 61), new Student("Kiran", 47), new Student("Divya", 75));
Card card = classA.stream() .collect(Collectors.teeing( Collectors.summarizingInt(Student::marks), Collectors.maxBy(Comparator.comparingInt(Student::marks)), (stats, top) -> new Card(stats, top.map(Student::name).orElse("none"))));
long passed = classA.stream().filter(s -> s.marks() >= 40).count(); IntSummaryStatistics s = card.stats();
System.out.println("Class A summary"); System.out.println("Students : " + s.getCount()); System.out.printf("Average : %.1f%n", s.getAverage()); System.out.println("Highest : " + s.getMax() + " (" + card.topper() + ")"); System.out.println("Lowest : " + s.getMin()); System.out.println("Passed : " + passed + " of " + s.getCount()); }}Class A summary Students : 6 Average : 66.3 Highest : 93 (Neha) Lowest : 34 Passed : 5 of 6
What this code does
teeingjoins two different kinds of result: the numbers fromsummarizingIntand the topper's name frommaxBy. The merger packs both into aCardrecord.top.map(Student::name).orElse("none")takes the name out of theOptionaland gives a safe default for an empty class. The Optional values module covers these methods fully.
The topper's name needs the student, not just the number, so teeing(summarizingInt(...), maxBy(...), ...) builds the whole card in a single collect call.
The same shape fits an expense card for a hostel mess, a UPI monthly statement, or the scorecard of a cricket series.
Next step
Check your understanding
11 quick questions