Java SE 8 Programmer II — Question 16
Given the code fragment:
List<String> codes = Arrays.asList ("DOC", "MPEG", "JPEG"); codes.forEach (c -> System.out.print(c + " "));
String fmt = codes.stream()
.filter (s-> s.contains ("PEG"))
.reduce((s, t) -> s + t).get();
System.out.println("\n" + fmt);
What is the result?
Answer options
- A. DOC MPEG JPEG MPEGJPEG
- B. DOC MPEG MPEGJPEG MPEGMPEGJPEG
- C. MPEGJPEG MPEGJPEG
- D. java.util.NoSuchElementException is thrown.
Correct answer: A
Explanation
The correct answer is A because the code prints each element in the list followed by a space, and then it concatenates the strings that contain 'PEG', which results in 'MPEGJPEG'. Therefore, the output is 'DOC MPEG JPEG MPEGJPEG'. Options B and C are incorrect as they do not accurately reflect the output of the code. Option D is also incorrect, as no exception is thrown in this case.