1Z0-809 · Question #236
Given the code fragment: List<String> gwords = Arrays.asList("why ", "what ", "when "); BinaryOperator<String> operator = (s1, s2) -> s1.concat(s2); // line n1 String sen = gwords.stream()…
The correct answer is A. Word: why what when. reduce(identity, accumulator) folds the stream left, starting with the identity and applying the accumulator once per element in sequence: "Word: " → concat("why ") → "Word: why " → concat("what ") → "Word: why what " → concat("when ") → "Word: why what when ". That single…
Question
Options
- AWord: why what when
- BWord: whyWord: why what Word: why what when
- CWord:why Word:what Word:when
- DCompilation fails at line n1.
How the community answered
(38 responses)- A79% (30)
- B8% (3)
- C11% (4)
- D3% (1)
Explanation
reduce(identity, accumulator) folds the stream left, starting with the identity and applying the accumulator once per element in sequence: "Word: " → concat("why ") → "Word: why " → concat("what ") → "Word: why what " → concat("when ") → "Word: why what when ". That single accumulated string is what gets printed, making A correct.
B is wrong because it shows three progressive sub-results concatenated together ("Word: why", "Word: why what", "Word: why what when"), as if each intermediate accumulation was appended to the output - reduce doesn't expose or accumulate intermediate results that way.
C is wrong because it implies the identity "Word: " was prefixed to each element individually, which would be a map operation, not a reduce.
D is wrong because line n1 compiles perfectly: a lambda (s1, s2) -> s1.concat(s2) matches BinaryOperator<String> exactly - two String parameters, one String return.
Memory tip: Think of reduce(identity, op) as a running total - the identity is your starting value and each stream element updates it exactly once, left to right. The final value, not any intermediate step, is what you get back.
Community Discussion
No community discussion yet for this question.