Predicate interfaces can be complicated, so be careful when working out the results.
April 6, 2020 | Download a PDF of this article
More quiz questions available here
If you have worked on our quiz questions in the past, you know none of them is easy. They model the difficult questions from certification examinations. The “intermediate” and “advanced” designations refer to the exams rather than to the questions, although in almost all cases, “advanced” questions will be harder. We write questions for the certification exams, and we intend that the same rules apply: Take words at their face value and trust that the questions are not intended to deceive you but to straightforwardly test your knowledge of the ins and outs of the language.
The objective here is to use core functional interfaces such as
Supplier. This specific quiz explores predicates.
Given this code fragment:
Predicate<Integer> p1 = (i1) -> i1 > 9;
Predicate<Integer> p2 = (i2) -> i2 % 2 == 0;
Predicate<Integer> p3 = (i3) -> i3 > 19;
boolean result = p1.and(p2.negate()).and(Predicate.not(p3)).test(i);
Which of the following arguments will cause the result to be
true? Choose two.
java.util.function.Predicate is a functional interface introduced in Java 8. The single abstract method—
boolean test(T t)—accepts a single parameter and returns a
Boolean. From the start, the interface provided the
negate(), which make it easy to compose conditions. With Java 11, the interface gained the
Predicate.not(Predicate p), which creates a predicate representing the negation of the predicate passed in.
The question presents three predicates. The first,
p1, tests to see if the argument is greater than 9. The second,
p2, tests if the argument is even. And the third,
p3, tests if the argument is greater than 19.
The last code line in this question has three predicates joined with a logical AND. The first is
p1, to see if the value is greater than 9. The second is the inverse of
p2, which will check for an odd value. The third will check if the value is less than or equal to 19 (the not, or inverse, of being greater than 19).
Only options C and D satisfy the overall condition. Their parameters are greater than 9, odd, and less than or equal to 19.
The correct answers are option C and option D.
Option A fails the first predicate check, which tests whether the parameter is greater than 9. So option A is incorrect.
Option B fails the second predicate check, which tests whether the parameter is odd. So Option B is incorrect.
Option E fails the third predicate check, which tests whether the parameter is less than or equal to 19. So option E is incorrect.