What is Collectors.summarizingInt() in Java?
What is the Collectors class?
Collectors is a utility class that provides various implementations of reduction operations, such as grouping elements, collecting elements in different collections, and summarizing elements according to various criteria. The different functions in the Collectors class are usually used as final operations in streams.
The summarizingInt() method
summarizingInt() is a static method of the Collectors class that is used to return the summary statistics of the results obtained from applying the passed ToIntFunction implementation to a set of input elements.
The following statistics are provided on the elements of the stream:
- Count of all the elements
- Cumulative sum of the elements
- Minimum element
- Maximum element
- Average of all the elements
The summarizingInt method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package. To import the Collectors class, use the following import statement.
import java.util.stream.Collectors;
Syntax
public static <T> Collector<T, ?, IntSummaryStatistics> summarizingInt(ToIntFunction<? super T> mapper)
Parameters
ToDoubleFunction<? super T> mapper: The function to extract the property/attribute to summarize.
Return value
This method returns the summary statistics of the elements returned as the result of the passed ToDoubleFunction implementation.
Code
import java.util.Arrays;import java.util.IntSummaryStatistics;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {public static void main(String[] args){List<Integer> integerList = Arrays.asList(23, 23, 8);System.out.println("Contents of the list - " + integerList);Stream<Integer> integerStream = integerList.stream();IntSummaryStatistics intSummaryStatistics = integerStream.collect(Collectors.summarizingInt(e -> e));System.out.println("Summary statistics of the stream - " + intSummaryStatistics);}}
Explanation
- Lines 1-5: We import the relevant packages.
- Line 11: We define a list of
intvalues calledintegerList. - Line 13: We print
integerList. - Line 15: We create a stream out of
integerList. - Line 17: We use the
summarizingIntmethod to find the summary statistics of the elements ofintegerList. Here, the passedToIntFunctionimplementation returns the passed element itself. - Line 19: We print the statistics obtained in line 16.