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.
averagingDouble()
methodaveragingDouble()
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;
public static <T> Collector<T, ?, Double> averagingDouble(ToDoubleFunction<? super T> mapper)
ToDoubleFunction<? super T> mapper
: The function to extract the property/attribute to be averaged.
This method returns the average/arithmetic mean of the elements returned as the result of the passed ToDoubleFunction
implementation.
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);}}
double
values called doubleList
.doubleList
.doubleList
.doubleList
using the averagingDouble
method. Here, the passed ToDoubleFunction
implementation returns the passed element itself.