Reputation: 3050
Say , i have List of Emp object with name, age and salary attribute .
List<Emp> empObj = readEmpDetails();
Keeping filter condition from DB or read from flat file. But syntax like below format.
name contains mike
age gt 100
How can i convert list of above condition to java expression . need to perform this condition against empObj which we read from DB source. How can i do this ? Please share your experience.
Upvotes: 1
Views: 1491
Reputation: 3572
You could use Spring Spel (org.springframework.expression.ExpressionParser
):
public static void main(String[] args) {
List<Emp> emp = Arrays.asList(new Emp("Ann", 25, 1000L)
,new Emp("John", 40, 2000L)
,new Emp("Alex", 60, 3000L));
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("age gt 30");
emp.stream()
.filter(emp1 -> exp.getValue(emp1, Boolean.class))
.forEach(emp1 -> System.out.println(emp1.getName() + " " + emp1.getAge()));
}
Output:
John 40
Alex 60
Types of literals and operations are:
Upvotes: 3
Reputation: 551
Based on your request, I'll make code like the following.
public boolean filter(String name, String search, int age) {
boolean a = name.contains(search/* mike */);
boolean b = (age >= 100);
return a & b;
}
The following code is second way after I checked you reply.
public ArrayList<Emp> filter() {
ArrayList<Emp> results = new ArrayList<>();
this.emps.stream()
.filter(Main::wordFilterFunc)
.filter(Main::ageFilterFunc)
.forEach(emp -> results.add(emp));
return results;
}
private static boolean wordFilterFunc(Emp word){
// implement what you want
}
private static boolean ageFilterFunc(Emp word){
// implement what you want
}
Upvotes: 0