Learn Hadoop
Learn Hadoop

Reputation: 3050

Java evaluate string as expression or code execution

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

Answers (2)

i.bondarenko
i.bondarenko

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:

  • Literals:
    • Text literals: 'one text', 'Another one!',…
    • Number literals: 0, 34, 3.0, 12.3,…
    • Boolean literals: true, false
    • Null literal: null
    • Literal tokens: one, sometext, main,…
  • Text operations:
    • String concatenation: +
    • Literal substitutions: |The name is ${name}|
  • Arithmetic operations:
    • Binary operators: +, -, *, /, %
    • Minus sign (unary operator): -
  • Boolean operations:
    • Binary operators: and, or
    • Boolean negation (unary operator): !, not
  • Comparisons and equality:
    • Comparators: >, <, >=, <= (gt, lt, ge, le)
    • Equality operators: ==, != (eq, ne)
  • Conditional operators:
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)

Upvotes: 3

libliboom
libliboom

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

Related Questions