Return to site

☕🎓JAVA CERTIFICATION QUESTION: Stream and Identity

Given the properly initialized stream

Stream s = ... // initialize stream

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

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

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

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

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

#java #certificationquestion #ocp

Answer:

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 IntStream.map() operation returns an IntStream, and a Stream.map() returns another reference type, Stream.

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

and

IntStream is = s.map(i -> 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.

With:

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.