Summarizing Statistics

summaryStatistics() is a terminal operation on a primitive stream (IntStream, LongStream, DoubleStream) that computes count, sum, min, max, and average in a single pass.

Key Points: • Call mapToInt (or mapToLong/mapToDouble) first to get a primitive stream, then invoke summaryStatistics(). • The returned IntSummaryStatistics object exposes getCount(), getSum(), getMin(), getMax(), and getAverage(). • Computing all five statistics in one pass is more efficient than calling separate terminal operations like sum() and max() individually. • It's especially useful in reporting or analytics code that needs several aggregate values from the same numeric dataset. • For an empty stream, getMin() and getMax() return sentinel-safe defaults, and getAverage() returns 0.0.

Example: Given a list of order totals, calling summaryStatistics() lets you print the total revenue, the average order size, and the largest order in a single line instead of three separate stream passes.

Code Example:

IntSummaryStatistics stats = numbers.stream()
        .mapToInt(Integer::intValue)
        .summaryStatistics();

System.out.println(stats.getMax() + " " + stats.getAverage());

Interview Tip: A concise interview answer is:

"summaryStatistics() on an IntStream gives me count, sum, min, max, and average from a single pass over the data, via the returned IntSummaryStatistics object. It's more efficient than chaining separate sum(), max(), and average() calls when I need several aggregates at once."