Java | Collectors averagingDouble() with Examples
Last Updated :
06 Dec, 2018
Collectors averagingDouble(ToDoubleFunction<? super T> mapper) method is used to find the mean of the double values passed in the parameters. This method returns a Collector that produces the arithmetic mean of an double-valued function applied to the input elements. If no elements are passed as the input elements, then this method returns 0.
The formula used by this method to calculate
arithmetic mean is:
Syntax:
public static <T>
Collector<T, ?, Double>
averagingDouble(ToDoubleFunction<? super T> mapper)
where the terms are as follows:
- Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.
- T: The type of input elements to the reduction operation.
- A: The mutable accumulation type of the reduction operation.
- R: The result type of the reduction operation.
- Double: The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.
- ToDoubleFunction: Represents a function that produces a double-valued result.
Parameters: This method accepts a parameter
mapper which is double-valued stream converted into Double using ToDoubleFunctions.
ToDoubleFunction is a function which extracts a double type of value as it works on the objects of the stream.
Below are examples to illustrate averagingDouble() method:
Program 1:
import java.util.stream.Collectors;
import java.util.stream.Stream;
class GFG {
public static void main(String[] args)
{
Stream<String> s = Stream.of( "3" , "4" , "5" );
double ans = s
.collect(Collectors
.averagingDouble(
num -> Double.parseDouble(num)));
System.out.println(ans);
}
}
|
Program 2:
import java.util.stream.Collectors;
import java.util.stream.Stream;
class GFG {
public static void main(String[] args)
{
Stream<String> s = Stream.of( "7" , "8" , "9" , "10" );
double ans = s
.collect(Collectors
.averagingDouble(
num -> Double.parseDouble(num)));
System.out.println(ans);
}
}
|
Program 3: When no value is passed as parameter.
import java.util.stream.Collectors;
import java.util.stream.Stream;
class GFG {
public static void main(String[] args)
{
Stream<String> s = Stream.of();
double ans = s
.collect(Collectors
.averagingDouble(
num -> Double.parseDouble(num)));
System.out.println(ans);
}
}
|
Share your thoughts in the comments
Please Login to comment...