193. Using BiPredicate
Let’s consider the Car model and a List<Car> denoted as cars:
public class Car { private final String brand; private final String fuel; private final int horsepower; ... } Our goal is to see if the following Car is contained in cars:
Car car = new Car("Ford", "electric", 80); We know that the List API exposes a method named contains(Object o). This method returns true if the given Object is present in the given List. So, we can easily write a Predicate, as follows:
Predicate<Car> predicate = cars::contains; Next, we call the test() method, and we should get the expected result:
System.out.println(predicate.test(car)); // true We can obtain the same result in a stream pipeline via filter(), anyMatch(), and so on. Here is via anyMatch():
System.out.println( cars.stream().anyMatch(p -> p.equals(car)) ); Alternatively, we can rely on BiPredicate. This is a functional...