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.
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;
public static <T> Collector<T, ?, Double> averagingLong(ToLongFunction<? super T> mapper)
ToLongFunction<? super T> mapper
: The function to extract the property/attribute to be averaged.This method returns the average of the elements returned as a result of applying the passed ToLongFunction
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<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);}}
long
values called longList
.longList
.longList
.longList
using the averagingLong
method. Here, the passed ToLongFunction
implementation returns the passed element itself.