Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

The IntSummaryStatistics class

Reference for IntSummaryStatistics, LongSummaryStatistics and DoubleSummaryStatistics: get count, sum, min, max and average in a single pass over a stream.

IntSummaryStatistics collects five numbers in one pass: the count, sum, minimum, maximum and average of a set of int values. Without it you would need up to five separate stream traversals, and a stream can only be traversed once.

You usually get one from IntStream.summaryStatistics() or the collectors Collectors.summarizingInt(), summarizingLong() and summarizingDouble(). LongSummaryStatistics and DoubleSummaryStatistics are the matching types for those value kinds.

Java
IntSummaryStatistics s = IntStream.of(4, 8, 15).summaryStatistics();
s.getMax();      // 15
s.getAverage();  // 9.0

Try it

Java Statistics from a stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Empty input, accept and combine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public class IntSummaryStatistics implements IntConsumer
Member Description
IntSummaryStatistics() Creates empty statistics.
accept(int value) Adds one value.
combine(IntSummaryStatistics other) Merges another summary into this one.
getCount() Number of values (long).
getSum() Sum as a long.
getMin(), getMax() Extremes as int.
getAverage() double, 0.0 when empty.
toString() Readable form such as IntSummaryStatistics{count=3, sum=27, min=4, average=9.000000, max=15}.

DoubleSummaryStatistics has double sum, min and max.

Usage notes

  • Empty case: getMin() returns Integer.MAX_VALUE and getMax() returns Integer.MIN_VALUE; check getCount() > 0 before trusting them.
  • Sum type: the sum is a long, so it is safer than IntStream.sum().
  • One pass: use it instead of calling min(), max() and average() separately on the same stream, which would throw IllegalStateException on reuse.
  • Not thread-safe by itself: accept is not atomic. The collectors and parallel streams handle merging through combine().
  • Double sums: DoubleSummaryStatistics uses compensated (Kahan-style) summation, so results are more accurate than a naive loop but can still differ in the last digits.
  • Grouped statistics: combine Collectors.groupingBy() with summarizingInt() to get statistics per group.