nerdexam
Oracle

1Z0-809 · Question #86

Given the code fragment: Arrays.asList ("1", "John"), Arrays.asList ("2", null)); Stream<String> jInst = iStr.flatMapToTnt ((x -> x.stream ())); jInst.forEach (System.out :: print); What is the…

The correct answer is D. A compilation error occurs. Option D is correct because flatMapToInt is the wrong method - it expects a Function<T, IntStream> and returns an IntStream, but the lambda x -> x.stream() returns a Stream<String>, not an IntStream. The compiler catches both mismatches (wrong lambda return type and…

Question

Given the code fragment: Arrays.asList ("1", "John"), Arrays.asList ("2", null)); Stream<String> jInst = iStr.flatMapToTnt ((x -> x.stream ())); jInst.forEach (System.out :: print); What is the result?

Options

  • A1John2null
  • B12
  • CA NullPointerException is thrown at run time.
  • DA compilation error occurs.

How the community answered

(37 responses)
  • A
    8% (3)
  • B
    5% (2)
  • C
    16% (6)
  • D
    70% (26)

Explanation

Option D is correct because flatMapToInt is the wrong method - it expects a Function<T, IntStream> and returns an IntStream, but the lambda x -> x.stream() returns a Stream<String>, not an IntStream. The compiler catches both mismatches (wrong lambda return type and incompatible assignment to Stream<String>), so the code never runs.

Option A (1John2null) is wrong because it assumes flatMap was used correctly - the code never compiles to produce any output. Option C (NullPointerException) is a plausible distractor since null appears in the list, but System.out.print(null) handles null fine, and again the code never reaches runtime. Option B (12) has no basis - it imagines only the numeric elements are printed, which isn't how any stream operation here would behave.

Memory tip: Whenever you see flatMapToInt, flatMapToLong, or flatMapToDouble on an object stream, the lambda must return the matching primitive stream type (IntStream, LongStream, DoubleStream). Using a generic Stream<T> lambda with a primitive-specialized flatMapTo* method is always a compile error - remember "primitive method, primitive stream."

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice