What is the Collectors.summingInt() method in Java?

Share

What is the Collectors class?

Collectors is a utility class, which provides various implementations of reduction operations, such as grouping elements, collecting elements to different collections, summarizing elements according to various criteria, and so on. The different functionalities in the Collectors class are usually used as the final operation on streams.

summingInt() method

summingInt() is a static method of the Collectors class, which is used to return a Collector. This Collector calculates the sum of the result that is returned after we apply the passed ToIntFunction implementation to the input elements. If there are no elements, then the method returns 0.

The summingInt method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package. To import the Collectors class, we check the following import statement:

import java.util.stream.Collectors;

Syntax


public static <T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper)

Parameters

  • ToIntFunction<? super T> mapper: This is the function that is used to extract the property/attribute that needs to be summed.

Return value

This method returns the sum of the elements that are returned as a result of us applying the passed ToIntFunction implementation to all the input elements.

Code

import java.util.Arrays;
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();
int sumOfElements = integerStream.collect(Collectors.summingInt(e -> e));
System.out.println("Sum of the stream - " + sumOfElements);
}
}

Code explanation

  • Lines 1–4: We import the relevant packages.
  • Line 10: We define a list of int values called integerList.
  • Line 12: We print the integerList.
  • Line 14: We create a stream out of the integerList.
  • Line 16: We find the sum of the elements of the integerList, using the summingInt method. Here, the passed ToIntFunction implementation returns the passed element itself.
  • Line 18: We print the sum of the elements of the stream.