1Z0-809 practice question 11 of 25

Given the code fragment: Stream iStr= Stream.of ( Arrays.asList (“1”, “John”), Arrays.asList (“2”, null)0; Stream x.stream ()); nInSt.forEach (System.out :: print); What is the result?

Full set: 196 questions
Answer options
A: 1John2null
B: 12
C: A NullPointerException is thrown at run time.
D: A compilation error occurs. Correct answer
Correct Answer:
D. A compilation error occurs.
Explanation

A compilation error occurs because of a type mismatch in the stream pipeline. The flatMapToInt method is a specialized flat-map operation that is required to return an IntStream. The lambda expression provided, (x) -> x.stream(), where x is a List, returns a Stream. The compiler cannot implicitly convert a Stream to an IntStream, resulting in a type-incompatibility error.

Why Incorrect

A. This output would be possible if flatMap was used instead of flatMapToInt, but the given code does not compile.
B. The code fails to compile. To get integer output, a mapping operation like mapToInt would be needed after flattening, which is not present.
C. A NullPointerException is a runtime exception. The issue in this code is a compile-time type error, which prevents the program from running.

References

- Java SE 8 Platform API Specification, java.util.stream.Stream.flatMapToInt(Function mapper). The documentation specifies that the mapper function must produce an IntStream.

- Oracle, The Java™ Tutorials, "Aggregate Operations". The section on stream operations distinguishes between generic streams (Stream) and primitive streams (IntStream, LongStream, DoubleStream) and their specific mapping operations.

Scroll to Top