Externally configurable filtering using Java lambdas

Viewed 636

Lets say I have an external JSON as:

[{
    "condition": "equals",
    "field": "name",
    "value": "jack"
  },
  {
    "condition": "greater",
    "field": "age",
    "value": 25
  }
]

What this means is I want to check, in a list of Person objects for people with name as "jack" and age > 25. It is fairly simple with Java 8 filtering(example shown is filtering just on name).

However, I want to make this filter configurable and also apply multiple filters. Assuming the Person pojo below (which is self-explanatory), takes name and age, how can I make the filters dynamic or configurable?

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Accessors and Mutators
}
List<Person> persons = Arrays.asList(
    new Person("mkyong", 30),
    new Person("jack", 20),
    new Person("lawrence", 40)
);

Person result1 = persons.stream()            // Convert to steam
    .filter(x -> "jack".equals(x.getName())) // we want "jack" only
    .findAny()                               // If 'findAny' then return found
    .orElse(null);  

I am expecting a list of Person object which satisfy the criterion as a result.

2 Answers
Related