How to use method with Predicate parameter, without using lambda expression

71 Views Asked by At

I am working on a Post Office Storage exercise, where some of the methods are using another method searchBoxes whose parameter is a Predicate. I have to implement those methods using searchBoxes, but I must not use a lambda expression like I already do.

This is the searchBoxes method I have to use:

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;
}

And this is one of the other methods:

public List<Box> getAllWeightLessThan(double weight) {
    if(weight < 1) {
        throw new IllegalArgumentException();
    }
    List<Box> result = searchBoxes(e -> e.getWeight() < weight);
    return result;
}

What I have to do is to avoid the lambda expression where I call the searchBoxes method: searchBoxes(e -> e.getWeight() < weight);, but the problem is that I must use the searchBoxes method.

How is it possible to avoid this and call the method in same way but without a lambda?

1

There are 1 best solutions below

1
Chaosfire On BEST ANSWER

Just make a normal implementation:

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;
  }
}

And usage:

List<Box> result = searchBoxes(new MaxWeightPredicate(weight));

Or use anonymous class, but you have to declare it in a place with access to weight:

Predicate<Box> predicate = new Predicate<Box>() {
  @Override
  public boolean test(Box box) {
    return box.getWeight() < weight;
  }
};