我正在进行邮局存储练习,其中部分方法使用另一种方法
searchBoxes
,其参数是谓词。我必须使用 searchBoxes
来实现这些方法,但我不能像我已经做的那样使用 lambda 表达式。
这是我必须使用的
searchBoxes
方法:
public List<Box> searchBoxes(Predicate<Box> predicate) {
if(predicate == null) {
throw new NullPointerException();
}
List<Box> selected = new LinkedList<>();
for(Box box : parcels) {
if(predicate.test(box)) {
selected.add(box);
}
}
return selected;
}
这是其他方法之一:
public List<Box> getAllWeightLessThan(double weight) {
if(weight < 1) {
throw new IllegalArgumentException();
}
List<Box> result = searchBoxes(e -> e.getWeight() < weight);
return result;
}
我要做的就是避免调用
searchBoxes
方法时的 lambda 表达式:searchBoxes(e -> e.getWeight() < weight);
,但问题是我必须使用 searchBoxes
方法。
如何避免这种情况并以相同的方式调用该方法但没有 lambda?
正常实现即可:
public class MaxWeightPredicate implements Predicate<Box> {
private final double maxWeight;
public MaxWeightPredicate(double maxWeight) {
this.maxWeight = maxWeight;
}
@Override
public boolean test(Box box) {
return box.getWeight() < this.maxWeight;
}
}
及用法:
List<Box> result = searchBoxes(new MaxWeightPredicate(weight));
或者使用匿名类:
Predicate<Box> predicate = new Predicate<>() {
@Override
public boolean test(Box box) {
return box.getWeight() < weight;
}
};