194. Building a dynamic predicate for a custom model
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;
...
}
Also, let’s assume that we need to dynamically produce a wide range of predicates that apply the operators <
, >
, <=
, >=
, !=
, and ==
to the horsepower
field. It will be cumbersome to hardcode such predicates, so we have to come up with a solution that can build, on the fly, any predicate that involves this field, and one of the comparison operators listed here.
There are a few approaches to accomplish this goal, and one of them is to use a Java enum
. We have a fixed list of operators that can be coded as enum
elements, as follows:
enum PredicateBuilder {
GT((t, u) -> t > u),
LT((t, u) -> t < u),
GE((t, u) -> t >= u),
LE((t, u) -> t <= u),
EQ((t, u) -> t.intValue() == u...