check each object, return true when the first condition is met, else return false

Viewed 43

I have a method that works fine. This is how it looks.

private ArrayList<Car> carsInStore ; //in car class have setter/getter/quals/Constructor.
public boolean checkIfcarInStore(Car c) {   
    for (Car car : carsInStore) {
        if(car.equals(c)){
            return true;
        }
    }
}

I want to switch this to Lambda.

But I am not sure how fill in the if (condition) return true or return false outside.

And I know I can do it in stream too. Can anyone give an example?

2 Answers

If you really want to use lambda, this should work else you have your answer within your comment.


private ArrayList<Car> carsInStore ;

public boolean checkIfcarInStore(Car c) {   
    return carsInStore.stream().anyMatch(c::equals);
    }
 }

You can substitute the method checkIfcarInStore() with a Predicate, which is a functional interface representing a boolean condition, that can be implemented as a lambda expression:

Predicate<Car> isInStore = car -> carsInStore.contains(car);

or as a method reference:

Predicate<Car> isInStore = carsInStore::contains;

If according to the instructions of your assignment you need to have a method checkIfcarInStore(), the predicate can be declared as a field and used internally inside the method:

private ArrayList<Car> carsInStore ;
private Predicate<Car> isInStore = car -> carsInStore.contains(car);
    
public boolean checkIfCarInStore(Car car) {
    return isInStore.test(car);
}
Related