Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Collectors.summingLong() 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 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.

The summingLong() method

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

The summingLong method is defined in the Collectors class, which 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, ?, Long> summingLong(ToLongFunction<? super T> mapper)

Parameters

  • ToLongFunction<? super T> mapper: 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 applying the passed ToLongFunction 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<Long> longList = Arrays.asList(2343L, 2332L, 876567L);

        System.out.println("Contents of the list - " + longList);

        Stream<Long> longStream = longList.stream();

        long sumOfElements = longStream.collect(Collectors.summingLong(e -> e));

        System.out.println("Sum of the stream - " + sumOfElements);
    }
}
Implementation of the "summingLong" method

Code explanation

  • Lines 1–4: We import the relevant packages.
  • Line 10: We define a list of long values called longList.
  • Line 12: We print longList.
  • Line 14: We create a stream out of longList.
  • Line 16: We use the summingLong method to find the sum of the elements of longList. Here, the passed ToLongFunction implementation returns the passed element itself.
  • Line 18: We print the sum of the elements of the stream.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring