![]() |
VOOZH | about |
In Java, the IntStream summaryStatistics() method returns an IntSummaryStatistics object that provides various summary statistics about the elements in the IntStream. This includes the count, average, minimum, maximum, and sum of the elements. This method is a terminal operation, i.e., it may traverse the stream to produce a result or a side-effect.
In this article, we are going to discuss how IntStream.summaryStatistics() simplifies the process of computing statistical measures in Java streams.
The declaration is:
IntSummaryStatistics summaryStatistics()
It is a class in java.util package that collects statistics such as:
IntStream summaryStatistics() is a special case of a reduction. A reduction, also known as a fold, combines the elements of a stream using a combining function such as summing values, finding the maximum, etc. summaryStatistics() offers a concise way to gather all of them at once, instead of using separate operations for each metric.
Now, we are going to discuss some examples for better understanding.
Example 1: Using IntStream summaryStatistics() to get the IntSummaryStatistics of elements present in given IntStream.
IntSummaryStatistics{count=4, sum=22, min=4, average=5.500000, max=7}
Explanation: Here, in this example, we are using IntStream.summaryStatistics() to calculate the count, sum, min, average and max for the input stream and then printing the output.
Example 2: Using IntStream summaryStatistics() to get the IntSummaryStatistics of elements in a given range.
IntSummaryStatistics{count=4, sum=26, min=5, average=6.500000, max=8}
Explanation: Here, in this example we are creating an IntStream with elements in the range from 5 and 8 with the help of IntStream.range(5,9) and then we are calculating count, sum, min, average and max and then printing the output.
The summaryStatistics() method is useful in many scenarios which are listed below:
The advantages of summaryStatistics() method is listed below: