OCP Question 18, Explanation

Given the code fragment:

List<String> ad = Arrays.asList(
    "See", "Java", "run.",
    "Run", "Java", "run.");
Predicate<String> test = x -> {
    int i = 0;
    boolean hit = x.contains("Java");
    System.out.print(i++ + " - ");
    return hit;
};
ad.stream()
  .filter(test)
  .findFirst()
  .ifPresent(System.out::print);

What is the result?

A. 0 – 0 – Java
B. 0 – 1 – Java
C. 0 – 0 – 0 – 0 – 0 – 0 – Java
D. 0 – 1 – 2 – 3 – 4 – 5 – 6 –
E. A compilation error occurs

 

The correct answer is A.

The value of i++ gets printed whenever the code calls filter() ► although findFirst() is a terminal op, there’s no comperr because ifPresent() is invoked on the Optional that findFirst() returns ► as the execution short-circuits at the first “Java”, only two numbers are printed, and every one of them equals zero because calls to the Predicate reset the i var each time. Finally, the code adds “Java” to the output.

Also note the use of ifPresent() and watch “The Mother of all Bikesheds” by Stuart Marks, https://www.youtube.com/watch?v=Ej0sss6cq14, where Stuart discusses pitfalls of fluent programming when using Optional. The video of Brian Goetz being interviewed by Angelica Langer that Stuart refers to @35:50 is here: https://jaxenter.de/fragen-und-antworten-zu-java-8-qa-33108, jump to ~16:07 where Brian starts talking on Optional’s get().

Leave Comment

Your email address will not be published.