Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Java Stream Summary Statistics [Snippets]

DZone's Guide to

Using Java Stream Summary Statistics [Snippets]

Here's a quick tip for those working with terminal stream operations: See how and when you can use the summaryStatistics method.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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()
        .mapToInt(Person::getAge)
        .min()
        .orElseThrow(NoSuchElementException::new);

int max = list.stream()
        .mapToInt(Person::getAge)
        .max()
        .orElseThrow(NoSuchElementException::new);


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

IntSummaryStatistics statistics = list.stream()
        .mapToInt(Person::getAge)
        .summaryStatistics();

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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,java streams ,summary statistics

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}