The Collectors.summarizingInt
method is actually similar to the summaryStatistics we discussed in the previous example. It returns a special class (IntSummaryStatistics
) which encapsulates a set of summary statistical values for a stream of integers.
Here’s an example:
package org.kodejava.stream;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
public class SummarizingIntExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Highest number in List : " + stats.getMax());
System.out.println("Lowest number in List : " + stats.getMin());
System.out.println("Sum of all numbers : " + stats.getSum());
System.out.println("Average of all numbers : " + stats.getAverage());
System.out.println("Total numbers in List : " + stats.getCount());
}
}
Output:
Highest number in List : 10
Lowest number in List : 1
Sum of all numbers : 55
Average of all numbers : 5.5
Total numbers in List : 10
In this case, Collectors.summarizingInt
is used as the collector for the stream.collect
method. The Integer::intValue
method reference is provided to tell it how to convert the stream elements (which are Integer objects in this case) to int values. The stream.collect
method aggregates the input elements into a single summary result (the IntSummaryStatistics
object).
Similar to summaryStatistics()
, Collectors.summarizingInt()
also provides corresponding methods for Long
(Collectors.summarizingLong
) and Double
(Collectors.summarizingDouble
) values.