OCP Question 97, Explanation

Given the code fragment:

List<String> archives = Arrays.asList("ZIP", "RAR", "TAR");
archives.forEach(x -> System.out.print(x + " "));
String common = archives.stream()
     .filter(x -> x.contains("AR"))
     .reduce((x, y) -> x + y).get();
System.out.println("\n" + common);

What is the result?

A. ZIP RAR TAR
RARTAR
B. ZIP RAR RARTAR
RARRARTAR
C. RARTAR
RARTAR
D. The order of the output is unpredictable.

 

The correct answer is A.

 

The forEach() method leaves no doubt as to what the first printed line must contain: all three String elements in archives, thus eliminating options B and C. What’s more, these elements will be printed in their stated order because the javadoc for the Stream class says that

Streams are created with an initial choice of sequential or parallel execution. For example, Collection.stream() creates a sequential stream, and Collection.parallelStream() creates a parallel one.

Our code doesn’t have a parallelStream() invocation, therefore all streams in it are sequential, which eliminates option D.

Leave Comment

Your email address will not be published.