Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Collectors.summarizingInt() in Java?

abhilash

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:

  1. Count of all the elements
  2. Cumulative sum of the elements
  3. Minimum element
  4. Maximum element
  5. 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);
    }
}
Implementation of the "summarizingInt" method

Explanation

  • Lines 1-5: We import the relevant packages.
  • Line 11: We define a list of int values called integerList.
  • Line 13: We print integerList.
  • Line 15: We create a stream out of integerList.
  • Line 17: We use the summarizingInt method to find the summary statistics of the elements of integerList. Here, the passed ToIntFunction implementation returns the passed element itself.
  • Line 19: We print the statistics obtained in line 16.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring