1Z0-809 · Question #186
Given: public class Product { String name; int qty; public String toString() { return name; } public Product(String name, int qty) { this.name = name; this.qty = qty; } static class ProductFilter {…
The correct answer is B. Replace line n1 with: public static boolean isAvailable (Product p) { return p.qty >= 10; } Replace line n2 with: .filter (p -> p.ProductFilter.isAvailable (p)). Option B works because making isAvailable static allows it to be called directly on the ProductFilter class without needing an instance - the lambda p -> Product.ProductFilter.isAvailable(p) correctly passes each stream element into the static method, which returns true for qty…
Question
Options
- AImplement Predicate in the Product.ProductFilter class and replace line n2 with .filter (p -> p.ProductFilter.test (p))
- BReplace line n1 with: public static boolean isAvailable (Product p) { return p.qty >= 10; } Replace line n2 with: .filter (p -> p.ProductFilter.isAvailable (p))
- CReplace line n2 with: .filter (p -> Product::isAvailable)
- DReplace line n2 with: .filter (p -> Product::ProductFilter::isAvailable ())
How the community answered
(58 responses)- A7% (4)
- B78% (45)
- C12% (7)
- D3% (2)
Explanation
Option B works because making isAvailable static allows it to be called directly on the ProductFilter class without needing an instance - the lambda p -> Product.ProductFilter.isAvailable(p) correctly passes each stream element into the static method, which returns true for qty ≥ 10, so only "Speaker" (qty=20) passes through.
Why the others fail:
- A is wrong because
p.ProductFilteris not a valid expression -ProductFilteris a class name, not a field on aProductinstance, so you cannot obtain aPredicateinstance this way. - C is wrong because
p -> Product::isAvailableis invalid syntax - you cannot use a method reference as the body of a lambda that must return aboolean; also,isAvailabledoesn't exist directly onProduct. - D is wrong because chaining
::operators (Product::ProductFilter::isAvailable()) is not legal Java syntax - there is no double-colon chaining in method references.
Memory tip: For filter() to accept a method reference or lambda, the expression must evaluate to a boolean. If the method lives in a static nested class, make it static so you can call it as OuterClass.InnerClass.method(element) inside a lambda - no instance of the nested class required.
Community Discussion
No community discussion yet for this question.