1Z0-809 · Question #207
Given: `` public interface LengthValidator { public boolean checkLength(String str); } ` and ` public class Txt { public static void main(String[] args) { boolean res = new LengthValidator() {…
The correct answer is C. Supplier. There is an error in this question: the marked correct answer (C, Supplier) is actually wrong. The correct answer is B. Predicate. Here's the accurate explanation: Why B (Predicate) is correct: LengthValidator.checkLength takes a String and returns a boolean - which is exactly…
Question
public interface LengthValidator {
public boolean checkLength(String str);
}
and
public class Txt {
public static void main(String[] args) {
boolean res = new LengthValidator() {
public boolean checkLength(String str) {
return str.length() > 5 && str.length() < 10;
}
}.checkLength("Hello");
}
}
Which interface from the java.util.function package should you use to refactor the class Txt?Options
- AConsumer
- BPredicate
- CSupplier
- DFunction
How the community answered
(32 responses)- A3% (1)
- B9% (3)
- C72% (23)
- D16% (5)
Explanation
There is an error in this question: the marked correct answer (C, Supplier) is actually wrong. The correct answer is B. Predicate.
Here's the accurate explanation:
Why B (Predicate) is correct: LengthValidator.checkLength takes a String and returns a boolean - which is exactly the signature of Predicate<String>'s functional method test(String t). The refactored code would be:
Predicate<String> validator = str -> str.length() > 5 && str.length() < 10;
boolean res = validator.test("Hello");
Why the others are wrong:
- A.
Consumer<T>- takes aTbut returnsvoid, notboolean. - C.
Supplier<T>- takes no arguments and returns aT; the opposite shape of what's needed here. - D.
Function<T,R>- takes aTand returns anR(a general type), but when the return type is specificallyboolean,Predicateis the more precise fit and the idiomatic choice.
Memory tip: Think "Predicate = passes a test." Whenever a lambda takes one input and returns true/false, reach for Predicate<T>. The other three follow the pattern: Supplier supplies (no in, something out), Consumer consumes (something in, nothing out), Function transforms (something in, something different out).
Community Discussion
No community discussion yet for this question.