CKTIS / Java
Reductions and statistics
Reductions and statistics: A reduction combines elements into a result, while IntSummaryStatistics gathers count, sum, min, max, and average in one traversal of an integer stream.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
reductions statisticsA reduction combines elements into a result, while IntSummaryStatistics gathers count, sum, min, max, and average in one traversal of an integer stream.
Use summaryStatistics for one data-set report, and reduce only with an associative combining operation and neutral identity.
IntStream.sum returns int and can overflow; IntSummaryStatistics accumulates a long without overflow detection, and group averages need count weights.
For empty statistics count and sum are 0, average is 0.0, min is Integer.MAX_VALUE, and max is Integer.MIN_VALUE.
The first line 3 12 2 6 4.0 summarizes 2,4,6; the second 0 0 2147483647 -2147483648 0.0 exposes the exact empty-statistics contract.
Examples
import java.util.IntSummaryStatistics;
import java.util.Locale;
import java.util.stream.IntStream;
public class Main {
static void print(IntSummaryStatistics s) {
System.out.printf(Locale.ROOT, "%d %d %d %d %.1f%n", s.getCount(), s.getSum(), s.getMin(), s.getMax(), s.getAverage());
}
public static void main(String[] args) {
print(IntStream.of(2, 4, 6).summaryStatistics());
print(IntStream.empty().summaryStatistics());
}
}
Result
3 12 2 6 4.0 0 0 2147483647 -2147483648 0.0
The first line 3 12 2 6 4.0 summarizes 2,4,6; the second 0 0 2147483647 -2147483648 0.0 exposes the exact empty-statistics contract.