What is Collectors.summarizingLong() in Java?

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.

What is the summarizingLong() method?

summarizingLong() is a static method of the Collectors, which is used to return a Collector. This Collector computes the summary statistics for the results that are obtained after we apply the passed ToLongFunction implementation to the input elements.

The following statistics are provided on the elements of the stream:

  1. The count of all the elements
  2. The cumulative sum of the elements
  3. The minimum element
  4. The maximum element
  5. The average of all the elements

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

import java.util.stream.Collectors;

Syntax


public static <T> Collector<T, ?, LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper)

Parameters

  • ToLongFunction<? super T> mapper: This is the function that extracts the property/attribute that needs to be summarized.

Return value

This method returns the summary statistics of the elements that are returned to apply the passed ToLongFunction implementation to the input elements.

Code

import java.util.Arrays;
import java.util.List;
import java.util.LongSummaryStatistics;
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();
LongSummaryStatistics longSummaryStatistics = longStream.collect(Collectors.summarizingLong(e -> e));
System.out.println("Summary statistics of the stream - " + longSummaryStatistics);
}
}

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 the longList.
  • Line 14: We create a stream out of the longList.
  • Line 16: We find the average of the elements of the longList, using the summarizingLong method. Here, the passed ToLongFunction implementation returns the passed element itself.
  • Line 18: We print the statistics that we obtained in line 16.

Free Resources