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 doubles
List<Double> doubleList = Arrays.asList(10.4, 24.5, 54.1, 8.0,23.2);
// Define the implementation of ToDoubleFunction interface
ToDoubleFunction<Double> multiplyByTwo = e -> e * 2;
// apply the multiplyByTwo using mapToDouble function and print each value
doubleList.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 ToDoubleFunction interface called multiplyByTwo. Here, we multiply the input double value by 2.
  • Line 15: We apply the multiplyByTwo using the mapToDouble function and print the result.

Free Resources