What is Collectors.averagingDouble() 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 to different collections, summarizing elements according to various criteria, etc. The different functions in the Collectors class are usually used as the final operations on streams.
The averagingDouble() method
averagingDouble() is a static method of the Collectors class that is used to calculate the average of the results returned by applying the passed ToDoubleFunction implementation to a set of input elements. If there are no elements, then the method returns zero.
The averagingDouble 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> averagingDouble(ToDoubleFunction<? super T> mapper)
Parameters
ToDoubleFunction<? super T> mapper: The function to extract the property/attribute to be averaged.
Return value
This method returns the average/arithmetic mean of the elements returned as the result of the passed ToDoubleFunction implementation.
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<Double> doubleList = Arrays.asList(23.43, 23.32, 8.76567);System.out.println("Contents of the list - " + doubleList);Stream<Double> doubleStream = doubleList.stream();double averageOfElements = doubleStream.collect(Collectors.averagingDouble(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
doublevalues calleddoubleList. - Line 12: We print the
doubleList. - Line 14: We create a stream out of the
doubleList. - Line 16: We find the average of the elements of the
doubleListusing theaveragingDoublemethod. Here, the passedToDoubleFunctionimplementation returns the passed element itself. - Line 18: We print the average of the elements of the stream.