IntSummaryStatistics Example in Java

IntSummaryStatistics

IntSummaryStatistics provides different statistical data like max, min, average. This class is desinged to work with Java streams but can work with with out streams also.

Example

Following class shows an example of IntSummaryStatistics used with stream. It is used to print interesting information like max, min, average, sum and count. And then the accept method is used to add a new integer to the previous data passed as the numStream.
public class IntSummaryStatisticsExample {

  public static void main(String[] args) {
   
    Stream<Integer> numStream = Stream.of(1, 2, 3, 4, 5);
    IntSummaryStatistics summary = numStream.mapToInt(p-> p).summaryStatistics();
    
    System.out.println("Max From the Data is " + summary.getMax());
    System.out.println("Min From the Data is " + summary.getMin());
    System.out.println("Average From the Data is " + summary.getAverage());
    System.out.println("Sum From the Data is " + summary.getSum());
    System.out.println("Count From the Data is " + summary.getCount());
    
    //Add a new number to the stream
    System.out.println("\n");
    summary.accept(10);
    
    System.out.println("Max From the Data is " + summary.getMax());
    System.out.println("Min From the Data is " + summary.getMin());
    System.out.println("Average From the Data is " + summary.getAverage());
    System.out.println("Sum From the Data is " + summary.getSum());
    System.out.println("Count From the Data is " + summary.getCount());
   
  }
}
IntSummaryStatistics Example Max From the Data is 5 Min From the Data is 1 Average From the Data is 3.0 Sum From the Data is 15 Count From the Data is 5 Adding number 10 to the data Max From the Data is 10 Min From the Data is 1 Average From the Data is 4.166666666666667 Sum From the Data is 25 Count From the Data is 6
IntSummaryStatistics Example
Max From the Data is 5
Min From the Data is 1
Average From the Data is 3.0
Sum From the Data is 15
Count From the Data is 5

Adding number 10 to the data
Max From the Data is 10
Min From the Data is 1
Average From the Data is 4.166666666666667
Sum From the Data is 25
Count From the Data is 6

Conclusion

IntSummaryStatistics defined in java.util package and available since java 8 provides a way to calculate statistical information. It works with and with out stream.

1 comment :

Please leave your message queries or suggetions.