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 = numbers.stream()
.mapToInt(x -> x)
.summaryStatistics();
stats.getCount(); // 6
stats.getMin(); // 2
stats.getMax(); // 10
stats.getSum(); // 33
stats.getAverage(); // 5.5