1Z0-808 · Question #45
Person.java: public class Person { String name; int age; public Person(String n, int a) { name = n; age = a; } public String getName() { return name; } public int getAge() { return age; } }…
The correct answer is C. checkAge (iList, p-> p.getAge() > 40). Option C uses the correct lambda syntax for a Predicate<Person>: a single inferred-type parameter without parentheses, followed by an expression body that directly returns a boolean - which is exactly what Predicate<Person>.test(Person p) requires. Since Hank is 45, 45 > 40…
Question
Options
- AcheckAge (iList, () -> p. get Age () > 40);
- BcheckAge (iList, Person p -> p.getAge() > 40);
- CcheckAge (iList, p-> p.getAge() > 40);
- DcheckAge (iList, (Person p) -> {p.getAge() > 40;});
How the community answered
(33 responses)- A9% (3)
- B3% (1)
- C73% (24)
- D15% (5)
Explanation
Option C uses the correct lambda syntax for a Predicate<Person>: a single inferred-type parameter without parentheses, followed by an expression body that directly returns a boolean - which is exactly what Predicate<Person>.test(Person p) requires. Since Hank is 45, 45 > 40 evaluates to true, so he gets printed.
Why the others fail:
- A uses
()(no parameters), butPredicate<Person>requires exactly onePersonargument - this won't compile. - B is a syntax error: when you explicitly declare the parameter type, parentheses are mandatory - it must be
(Person p), notPerson p. - D uses a block body
{...}but omitsreturn. Inside a block body, you must writereturn p.getAge() > 40;- without it, the lambda returnsvoid, which doesn't satisfyPredicate<Person>.
Memory tip: Think of the lambda rules as "brackets need brackets" - explicit type needs (), block body needs return. When in doubt, the simplest form p -> expression is always valid for a single-parameter predicate.
Topics
Community Discussion
No community discussion yet for this question.