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
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)- A8% (2)
- B15% (4)
- C4% (1)
- D73% (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
maprequires a function that returns a value -System.out.printlnreturnsvoid, 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
forEachis a terminal operation - replacingpeekwithforEachon line n1 consumes and closes the stream there, making the subsequent.map()and.peek()calls unreachable (compile error sinceforEachreturnsvoid).
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.