External configurable filtering using java lambda
Suppose I have an external JSON:
[{ "condition": "equals","field": "name","value": "jack" },{ "condition": "greater","field": "age","value": 25 } ]
This means I want to check in the person object list of people named "Jack" and age > 25. Filtering using java 8 is quite simple (the example shown filters only on the name)
However, I want to make this filter configurable and apply multiple filters Assuming the following person POJO (which is self-evident), take the name and age, how can I make the filter 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 expect a list of qualified person objects
Solution
As far as I know, this has nothing to do with the flow itself The filter method is just a predicate and can be provided as an instance, such as from a factory method you can create
static Predicate<Person> fromName(String value){ return p -> p.getName().equals(value); }
Suppose you have another method:
static Predicate<Person> fromAge(int value) { return p -> p.getAge() == value; }
Because predict and,Predicate. Or exists, you can do this:
fromAge(12).and(fromName("jack"));
To link your predicates