Java SE 8 Programmer II Exam: Question Answer - Result of Code Fragment

Java SE 8 Programmer II Exam: Question Answer

Question

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?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The given code creates a List of Strings using Arrays.asList() method, and then applies a forEach() method on this list to print the elements of the list separated by a space. After that, the code filters the list using stream() method to get only those elements which contain the string "PEG" and then concatenates those strings using reduce() method. Finally, it prints the concatenated string on a new line.

Let's go through the code step by step:

rust
List<String> codes = Arrays.asList("DOC", "MPEG", "JPEG"); codes.forEach(c -> System.out.print(c + " "));

This code creates a list of strings with values "DOC", "MPEG", "JPEG" and then uses the forEach() method to print each element of the list, separated by a space. The output of this code is:

objectivec
DOC MPEG JPEG
rust
String fmt = codes.stream() .filter(s -> s.contains("PEG")) .reduce((s, t) -> s + t) .get(); System.out.println("\n" + fmt);

This code creates a stream of the codes list using stream() method, then filters the stream using filter() method to only keep the elements containing the string "PEG". The reduce() method is then applied to concatenate the remaining elements of the stream into a single string. Finally, the concatenated string is printed on a new line.

The output of this code is:

objectivec
MPEGJPEG

Therefore, the correct answer is (C) MPEGJPEG.