nerdexam
Oracle

1Z0-809 · Question #222

Given the code fragment: List<Integer> prices = Arrays.asList(3, 4, 5); prices.stream() .filter(e -> e > 4) .peek(e -> System.out.print ("Price " + e)) // line n1 .map(e -> e + 1) // line n2 .peek(n…

The correct answer is D. Replace line n3 with .forEach (n -> System.out.println ("New Price" + n)). Option D is correct because peek is a lazy intermediate operation - without a terminal operation, the entire stream pipeline never executes and nothing prints. Replacing line n3 with .forEach(n -> System.out.println("New Price " + n)) adds a terminal operation, which triggers…

Question

Given the code fragment: List<Integer> prices = Arrays.asList(3, 4, 5); prices.stream() .filter(e -> e > 4) .peek(e -> System.out.print ("Price " + e)) // line n1 .map(e -> e + 1) // line n2 .peek(n -> System.out.println ("New Price " + n)); // line n3 Which modification enables the code to print Price 5 New Price 4?

Options

  • AReplace line n2 with .map (n -> System.out.println ("New Price" + n ?)) and remove line n3
  • BReplace line n2 with .mapToInt (n -> n ?!) ;
  • CReplace line n1 with .forEach (e -> System.out.print ("Price" + e))
  • DReplace line n3 with .forEach (n -> System.out.println ("New Price" + n));

How the community answered

(26 responses)
  • A
    8% (2)
  • B
    15% (4)
  • C
    4% (1)
  • D
    73% (19)

Explanation

Option D is correct because peek is a lazy intermediate operation - without a terminal operation, the entire stream pipeline never executes and nothing prints. Replacing line n3 with .forEach(n -> System.out.println("New Price " + n)) adds a terminal operation, which triggers the full pipeline: filter retains only 5, the first peek prints "Price 5", map transforms 5 to 6, and forEach prints "New Price 6". (Note: the expected output in the question appears to contain a typo - the correct result is "New Price 6", not "New Price 4".)

Why the distractors are wrong:

  • A is wrong because map requires a function that returns a value - System.out.println returns void, making this a compile error. There is also still no terminal operation.
  • B is wrong because ?! is not valid Java syntax; it would not compile.
  • C is wrong because forEach is a terminal operation - replacing peek with forEach on line n1 consumes and closes the stream there, making the subsequent .map() and .peek() calls unreachable (compile error since forEach returns void).

Memory tip: Think of intermediate operations (filter, map, peek) as building a recipe, and terminal operations (forEach, collect, count) as actually cooking it - without a terminal operation, the stream is defined but never runs.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice