1Z0-809 · Question #108
Given the code fragment: ``java List<String> codes= Arrays.asList("DOC", "MPEG", "JPEG"); codes.forEach(c -> System.out.print(c + " ")); String mt = codes.stream() .filter(s-> s.contains("PEG"))…
The correct answer is A. DOC MPEG JPEG MPEGJPEG. Option A is correct because the forEach call iterates the ordered List in insertion order, printing DOC MPEG JPEG on the first line, while the stream filters for elements containing "PEG" - matching "MPEG" and "JPEG" - then reduce concatenates them left-to-right as "MPEGJPEG"…
Question
List<String> codes= Arrays.asList("DOC", "MPEG", "JPEG");
codes.forEach(c -> System.out.print(c + " "));
String mt = codes.stream()
.filter(s-> s.contains("PEG"))
.reduce( (s, t) -> s + t).get();
System.out.println("\n" + mt);
What is the result?Options
- ADOC MPEG JPEG MPEGJPEG
- BDOC MPEG JPEG MPEGPEGJPEG
- CMPEGJPEG
- DThe order of the output is unpredictable.
How the community answered
(58 responses)- A76% (44)
- B14% (8)
- C3% (2)
- D7% (4)
Explanation
Option A is correct because the forEach call iterates the ordered List in insertion order, printing DOC MPEG JPEG on the first line, while the stream filters for elements containing "PEG" - matching "MPEG" and "JPEG" - then reduce concatenates them left-to-right as "MPEGJPEG", which is printed on the second line.
B is wrong because "MPEGJPEG" does not contain a standalone "PEG" element; only "MPEG" and "JPEG" pass the filter, so there is no extra "PEG" segment to concatenate - "MPEGPEGJPEG" would only appear if "PEG" were its own list entry.
C is wrong because it omits the forEach output entirely; forEach is a terminal operation that eagerly prints all three elements before the stream pipeline even begins.
D is wrong because Arrays.asList returns a List, which has a guaranteed encounter order, and sequential List streams process elements in that order - unpredictability applies to unordered sources like HashSet.
Memory tip: Think of forEach as "print now, ask questions later" - it runs to completion before any stream chain begins, so always mentally execute it first, then trace the stream pipeline step by step (filter → reduce → get).
Community Discussion
No community discussion yet for this question.