Summary statistics on a Java 8 stream of numbers

Java 8 streams provide an easy way to calculate basic statistics on the values of a stream of numbers. We can use the summaryStatistics method to get the basic statistics: minimum, maximum, count, sum and average.

List<Integer> numbers = Arrays.asList(10, 3, 2, 5, 9, 4);
IntSummaryStatistics stats =
    .mapToInt(x -> x)
stats.getCount(); // 6
stats.getMin(); // 2
stats.getMax(); // 10
stats.getSum(); // 33
stats.getAverage(); // 5.5
Calculate minimum, maximum, sum, average and count on a Java stream of numbers.

Subscribe to Java 8 Resources

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.