IntStream summaryStatistics() in Java 8


In Java 8, the IntStream interface provides the summaryStatistics() method, which returns an IntSummaryStatistics object describing various summary statistics for the elements of the stream. This includes the count, sum, min, max, and average.

Here’s how you can use IntStream and summaryStatistics() method with an example:

IntStreamExample.java
package org.websparrow.stream;

import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;

public class IntStreamExample {

    public static void main(String[] args) {

        // Creating an IntStream
        IntStream numbersStream = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Using summaryStatistics() to get statistics
        IntSummaryStatistics stats = numbersStream.summaryStatistics();

        // Printing statistics
        System.out.println("Count: " + stats.getCount());
        System.out.println("Sum: " + stats.getSum());
        System.out.println("Min: " + stats.getMin());
        System.out.println("Max: " + stats.getMax());
        System.out.println("Average: " + stats.getAverage());
    }
}

Related Posts:

  1. Java Collections.min() and Collections.max() Methods
  2. Java 8 Collectors.partitioningBy() Method Example
  3. Java 8 Collectors.groupingBy() Method Example

Output:

console.log
Count: 10
Sum: 55
Min: 1
Max: 10
Average: 5.5

References

  1. summaryStatistics() – JavaDoc
  2. Class IntSummaryStatistics – JavaDoc

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.