What is the summaryStatistics() method in Java Stream API?

The summaryStatistics method is a handy utility in the Java Stream API that returns a special class (IntSummaryStatistics, LongSummaryStatistics, or DoubleSummaryStatistics) encapsulating a set of statistical values: the count, sum, minimum, maximum, and average of numbers in the stream.

Here’s a basic example using IntSummaryStatistics:

package org.kodejava.stream;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;

public class IntSummaryStatisticsExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        IntSummaryStatistics stats = numbers.stream()
                .mapToInt((x) -> x)
                .summaryStatistics();

        System.out.println("Highest number in List : " + stats.getMax());
        System.out.println("Lowest number in List  : " + stats.getMin());
        System.out.println("Sum of all numbers     : " + stats.getSum());
        System.out.println("Average of all numbers : " + stats.getAverage());
        System.out.println("Total numbers in List  : " + stats.getCount());
    }
}

Output of the code snippet:

Highest number in List : 10
Lowest number in List  : 1
Sum of all numbers     : 55
Average of all numbers : 5.5
Total numbers in List  : 10

In this example, mapToInt is used to convert the Integer stream to an IntStream, which can then use the summaryStatistics method.

The resulting IntSummaryStatistics object holds all the computed statistics, which can be accessed via its methods (getMax(), getMin(), getSum(), getAverage(), and getCount()).

It’s a quick and convenient way to get multiple useful statistics about a group of numbers. Similar functionality is provided for Long and Double streams via LongSummaryStatistics and DoubleSummaryStatistics, respectively.

The beauty of this method is that it gives you all those statistical information in one go, and you don’t need to iterate the stream multiple times to calculate different values.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.