IntSummaryStatistics Class in Java to Collect IntStream Statistics

In this post, we will introduce IntSummaryStatistics class in Java which collect statistics such as count of elements, the minimum, maximum, sum, and average of elements in an IntStream.

 
First let’s see the naive way getting statistics such as count, min, max, sum, and average of elements in an IntStream. It involves getting the Stream every time, and converting Optional to its corresponding primitive value for min, max and average operations.

 

Download   Run Code

Output:

Max is 5
Min is 1
Average is 3.0
Count is 5
Sum is 15

 
A better solution is to get an instance of IntSummaryStatistics, which give a state object for collecting statistics such as count, min, max, sum, and average.

 

1. IntSummaryStatistics With an Array

 

Download   Run Code

Output:

IntSummaryStatistics{count=5, sum=15, min=1, average=3.000000, max=5}
Max is 5
Min is 1
Average is 3.0
Count is 5
Sum is 15

 

2. IntSummaryStatistics With a Collection

 

Download   Run Code

Output:

IntSummaryStatistics{count=5, sum=15, min=1, average=3.000000, max=5}
Max is 5
Min is 1
Average is 3.0
Count is 5
Sum is 15

 
Please note that for an empty Stream, getMax() returns Integer.MIN_VALUE, getMin() returns Integer.MAX_VALUE, getAverage() returns 0.0, and both getCount() and getSum() returns 0.

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz