What is the Stream.mapToDouble method in Java?
Overview
mapToDouble() of the Stream interface returns a DoubleStream. The DoubleStream contains the results of the the ToDoubleFunction function’s provided implementation on the stream’s items.
Syntax
DoubleStream mapToInt(ToDoubleFunction<? super T> mapper)
Parameters
ToDoubleFunction<? super T> mapper: The mapper function to apply.
Return value
This method returns a new stream:
Code
import java.util.Arrays;import java.util.List;import java.util.function.ToDoubleFunction;public class Main{public static void main(String[] args) {// define the list of doublesList<Double> doubleList = Arrays.asList(10.4, 24.5, 54.1, 8.0,23.2);// Define the implementation of ToDoubleFunction interfaceToDoubleFunction<Double> multiplyByTwo = e -> e * 2;// apply the multiplyByTwo using mapToDouble function and print each valuedoubleList.stream().mapToDouble(multiplyByTwo).forEach(System.out::println);}}
Explanation
- Lines 1-3: We import the relevant packages.
- Line 9: We define a list of double values.
- Line 12: We define the implementation of the
ToDoubleFunctioninterface calledmultiplyByTwo. Here, we multiply the input double value by2. - Line 15: We apply the
multiplyByTwousing themapToDoublefunction and print the result.