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.
IntSummaryStatistics s = IntStream.of(4, 8, 15).summaryStatistics(); s.getMax(); // 15 s.getAverage(); // 9.0
Try it
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.
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
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()returnsInteger.MAX_VALUEandgetMax()returnsInteger.MIN_VALUE; checkgetCount() > 0before trusting them. - Sum type: the sum is a
long, so it is safer thanIntStream.sum(). - One pass: use it instead of calling
min(),max()andaverage()separately on the same stream, which would throwIllegalStateExceptionon reuse. - Not thread-safe by itself:
acceptis not atomic. The collectors and parallel streams handle merging throughcombine(). - Double sums:
DoubleSummaryStatisticsuses 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()withsummarizingInt()to get statistics per group.