What is the IntStream.mapToObj method in Java?
Overview
In Java, the mapToObj() method of the IntStream interface is used to return an object-valued stream. This stream has the results obtained by applying the implementation of the IntFunction functional interface.
Note:
mapToObj()is an intermediate operation. This operation is performed on a stream instance and results in a stream instance.
Syntax
<U> Stream<U> mapToObj(IntFunction<? extends U> mapper);
Parameters
IntFunction<? extends U> mapper: This is the implementation of theIntFunctioninterface.
Return value
This method returns a new object-valued stream.
Example
import java.util.stream.Stream;import java.util.stream.IntStream;class Main {public static void main(String[] args){IntStream stream = IntStream.rangeClosed(2, 7);Stream<Integer> integerStream = stream.mapToObj(Integer::bitCount);integerStream.forEach(System.out::println);}}
Explanation
- Lines 1–2: We import the relevant packages.
- Line 7: We use the
rangeClosed()method to create anIntStream. - Line 9: We use the
mapToObj(IntFunction mapper)of theIntStreaminterface to create a new stream calledintegerStream, which stores the number of set bits of each integer in the stream. - Line 11: We print
integerStream.