邮局存储练习:如何不使用Lambda调用带Predicate参数的searchBoxes方法
解决方案
有两种常见方式可以替代Lambda表达式来实现Predicate<Box>并传递给searchBoxes方法:
方法一:使用匿名内部类
直接在调用searchBoxes时,通过匿名内部类实现Predicate<Box>接口,重写test方法完成重量判断逻辑:
public List<Box> getAllWeightLessThan(double weight) { if(weight < 1) { throw new IllegalArgumentException(); } List<Box> result = searchBoxes(new Predicate<Box>() { @Override public boolean test(Box box) { return box.getWeight() < weight; } }); return result; }
方法二:自定义Predicate实现类
如果这个重量判断逻辑需要复用,可以单独定义一个实现Predicate<Box>的类,通过构造方法传入阈值重量:
1. 定义自定义Predicate类
public class WeightLessThanPredicate implements Predicate<Box> { private double maxWeight; public WeightLessThanPredicate(double maxWeight) { this.maxWeight = maxWeight; } @Override public boolean test(Box box) { return box.getWeight() < maxWeight; } }
2. 修改原方法调用
public List<Box> getAllWeightLessThan(double weight) { if(weight < 1) { throw new IllegalArgumentException(); } List<Box> result = searchBoxes(new WeightLessThanPredicate(weight)); return result; }
这两种方式都完全符合要求:没有使用Lambda表达式,同时依然通过调用searchBoxes方法来实现功能。
内容的提问来源于stack exchange,提问作者Kostadin Samardjiev
相关产品推荐
相关产品推荐

