Getting all

Is there a way to obtain the count, sum, average, min, and max in a single unitary operation?

Yes, there is! Whenever we need two or more of these operations, we can rely on Collectors.summarizingInt​(), summarizingLong(), and summarizingDouble(). These methods wrap these operations in IntSummaryStatistics, LongSummaryStatistics, and DoubleSummaryStatistics, respectively, as follows:

IntSummaryStatistics melonWeightsStatistics = melons
.stream().collect(Collectors.summarizingInt(Melon::getWeight));

Printing this object produces the following output:

IntSummaryStatistics{count=7, sum=15900, min=1600, average=2271.428571, max=3000}

For each of these operations, we have dedicated getters:

int max = melonWeightsStatistics.getMax()

We're all done! Now, let's talk about grouping elements of a stream.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.184.200