OCP Question 32, Explanation

Given the code fragment:

List<String> graces = Arrays.asList("faith", "hope", "love");
Predicate<String> test = x -> {
    System.out.println("Still waiting...");
    return x.contains("love");
      .filter(x -> x.length() >= 4)

What is the result?

A. Still waiting…
B. Still waiting…
Still waiting…
C. Still waiting…
Still waiting…
Still waiting…
D. A compilation error occurs.


The correct answer is A.


The Stream‘s filter() method is actually redundant here as every element in graces meets the specified condition (element’s length must be at least four), so entire list successfully passes the filter. However, since allMatch() is a short-circuiting terminal operation, as soon as it rejects the very first candidate that comes its way (“faith”), the method stops evaluating the Predicate object test, that’s why “Still waiting…” gets printed only once.

Leave Comment

Your email address will not be published.