191. Composing predicates in a Stream’s filters
A predicate (basically, a condition) can be modeled as a Boolean-valued function via the java.util.function.Predicate
functional interface. Its functional method is named test(T t)
and returns a boolean
.
Applying predicates in a stream pipeline can be done via several stream intermediate operations, but we are interested here only in the filter(Predicate p)
operation. For instance, let’s consider the following class:
public class Car {
private final String brand;
private final String fuel;
private final int horsepower;
public Car(String brand, String fuel, int horsepower) {
this.brand = brand;
this.fuel = fuel;
this.horsepower = horsepower;
}
// getters, equals(), hashCode(), toString()
}
If we have a List<Car>
and we want to express a filter that produces all the cars that are Chevrolets, then we can start by defining the proper Predicate
:
Predicate<Car> pChevrolets...