What is DoubleStream.mapToObj method in Java?
Overview
The mapToObj() is a method of DoubleStream interface used to return an object-valued stream containing the results of applying the implementation of the DoubleFunction functional interface.
Note:
mapToObj()is an intermediate operation. These operations are lazy. Intermediate operations run on aStreaminstance, and when they’re done, they return aStreaminstance as an output.
Syntax
<U> Stream<U> mapToObj(DoubleFunction<? extends U> mapper);
Parameters
DoubleFunction<? extends U> mapper: The implementation of theDoubleFunctioninterface.
Return value
This method returns a new object-valued stream.
Code
import java.util.stream.DoubleStream;import java.util.stream.Stream;class Main {public static void main(String[] args){// Create a DoubleStream using the of methodDoubleStream stream = DoubleStream.of(2.1, 4.5, 2.5);// Using DoubleStream mapToObj(DoubleFunction mapper)// create a new stream// to store the hexadecimal representation of the// elements in DoubleStreamStream<String> hexStream = stream.mapToObj(Double::toHexString);// Print an object-valued StreamhexStream.forEach(System.out::println);}}
Explanation
- Lines 1-2 - We import the relevant packages.
- Line 8 - We create a
DoubleStreamusing theof()method. - Line 14 - Using the
mapToObj(DoubleFunction mapper)of theDoubleStreaminterface we create a new stream calledhexStreamto store the hexadecimal representation of the elements inDoubleStream. - Line 17 - We print the
hexStream.