Return to site


Given the properly initialized stream

Stream s = ... // initialize stream

How can you convert it to the stream of primitives? Choose one.

* IntStream is =;

* IntStream is = s.mapToInt(Function.identity());

* IntStream is = -> i);

* IntStream is = s.mapToInt(i -> i);

#java #certificationquestion #ocp


Java provides four variations of the Stream type: Stream, IntStream, LongStream, and DoubleStream.

Any map(...) operation always returns a Stream of the same basic group.

That is, an operation returns an IntStream, and a returns another reference type, Stream.

IntStream is =;


IntStream is = -> i);

will fail because of this;

they both call a simple map operation on a stream of reference type,

and that will produce another stream of reference type.

The result is not assignment compatible with IntStream.

Let's check the two other suggestions.


IntStream is = s.mapToInt(i -> i);

This code works as required.

Let's check why the last suggestion is wrong:

IntStream is = s.mapToInt(Function.identity());

This is because the Function.identity() method creates an object that implements the interface Function.

In this context, E is determined to be Integer, and the expanded type is Function.

The compiler is faced with the generics system mandating that Function is not assignment compatible with ToIntFunction,

and the code fails to compile.