What is Collectors.averagingLong() in Java?

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, summarizing elements according to various criteria, etc. The different functions in the Collectors class are usually used as final operations in streams.

The averagingLong() method

averagingLong() is a static method of the Collectors class that is used to calculate the arithmetic mean/average of the results obtained from applying the passed ToLongFunction implementation to a set of input elements. If there are no elements, then the method returns zero.

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

import java.util.stream.Collectors;

Syntax


public static <T> Collector<T, ?, Double> averagingLong(ToLongFunction<? super T> mapper)

Parameters

  • ToLongFunction<? super T> mapper: The function to extract the property/attribute to be averaged.

Return value

This method returns the average of the elements 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();
double averageOfElements = longStream.collect(Collectors.averagingLong(e -> e));
System.out.println("Average of the stream - " + averageOfElements);
}
}

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 averagingLong method. Here, the passed ToLongFunction implementation returns the passed element itself.
  • Line 18: We print the average value of the elements of the stream.