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:
Output:
console.log
Count: 10
Sum: 55
Min: 1
Max: 10
Average: 5.5