What is the LongStream.mapToObj method in Java?

mapToObj() of the LongStream interface is an operation that returns an object-valued stream. The stream has the results of applying the implementation of the LongFunction functional interface.

Note: mapToObj() is an intermediate operation. These operations are lazyThey are delayed unless they become needed.. Intermediate operations are run on a Stream instance. When they are done, they return a Stream instance as an output.

Syntax


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

Parameters

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

Return value

This method returns a new object-valued stream.

import java.util.stream.LongStream;
import java.util.stream.Stream;
class Main {
public static void main(String[] args)
{
// Create a LongStream using the rangeClosed method
LongStream stream = LongStream.rangeClosed(2, 7);
// Using LongStream mapToObj(LongFunction mapper)
// create a new stream
// to store the bit count in the binary representation of the
// elements in LongStream
Stream<Integer> bitCountStream = stream.mapToObj(Long::bitCount);
// Print the object-valued Stream
bitCountStream.forEach(System.out::println);
}
}