Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
stream

What is the LongStream.mapToObj method in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}

RELATED TAGS

java
communitycreator
stream

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring