Home » Java » Core Java » Using Java Stream summary statistics

About Michael Scharhag

Michael Scharhag is a Java Developer, Blogger and technology enthusiast. Particularly interested in Java related technologies including Java EE, Spring, Groovy and Grails.

Using Java Stream summary statistics

Streams of primitive types (IntStream, etc.) provide a summaryStatistics() method that can be used to get multiple statistical properties of a stream (minimum value, average value, etc.).

Assume we have a list of people. Our goal is to get the minimum and maximum age of the people in the list using streams.

The problem here is that the computation of the minimum and maximum values are terminal stream operations. So we need to come up with our own reduction implementation or create a new stream for every computation. A naive implementation might look like this:

List<Person> list = Arrays.asList(
        new Person("John Blue", 28),
        new Person("Anna Brown", 53),
        new Person("Paul Black", 47)

int min = list.stream()

int max = list.stream()

Luckily Java provides a much simpler way to do this using the summaryStatistics() method:

IntSummaryStatistics statistics = list.stream()

int min = statistics.getMin();
int max = statistics.getMax();

IntSummaryStatistics also provides methods to obtain the count and sum of the stream elements.

You can find the full example code on GitHub.

Published on Java Code Geeks with permission by Michael Scharhag, partner at our JCG program. See the original article here: Using Java Stream summary statistics

Opinions expressed by Java Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Notify of

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

Inline Feedbacks
View all comments