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 a Stream instance, and when they’re done, they return a Stream instance as an output.

Syntax


<U> Stream<U> mapToObj(DoubleFunction<? extends U> mapper);

Parameters

  • DoubleFunction<? extends U> mapper: The implementation of the DoubleFunction interface.

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 method
DoubleStream 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 DoubleStream
Stream<String> hexStream = stream.mapToObj(Double::toHexString);
// Print an object-valued Stream
hexStream.forEach(System.out::println);
}
}

Explanation

  • Lines 1-2 - We import the relevant packages.
  • Line 8 - We create a DoubleStream using the of() method.
  • Line 14 - Using the mapToObj(DoubleFunction mapper) of the DoubleStream interface we create a new stream called hexStream to store the hexadecimal representation of the elements in DoubleStream.
  • Line 17 - We print the hexStream.

Free Resources