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()
methodsummingInt()
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;
public static <T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper)
ToIntFunction<? super T> mapper
: This is the function that is used to extract the property/attribute that needs to be summed.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.
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);}}
int
values called integerList
.integerList
.integerList
.integerList
, using the summingInt
method. Here, the passed ToIntFunction
implementation returns the passed element itself.