List Selection
The Spring Expression Language (SpEL ) is a simple and powerful expression language
which helps to query and manipulate objects at runtime.
The following example shows using selection operator (?[selectionExpression] ).
It filters the collection and returns a new collection containing a subset of the original elements.
The selection criteria is evaluated against each individual element in the list.
package com.bethecoder.tutorials.spring3.tests.spel;
import java.util.ArrayList;
import java.util.List;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import com.bethecoder.tutorials.spring3.basic.Employee;
public class ListSelectionTest {
/**
* @param args
*/
public static void main ( String [] args ) {
StandardEvaluationContext stdContext = new StandardEvaluationContext () ;
List<Employee> employees = new ArrayList<Employee> () ;
employees.add ( new Employee ( 1 , "ONE" , 1111 )) ;
employees.add ( new Employee ( 2 , "TWO" , 2222 )) ;
employees.add ( new Employee ( 3 , "THREE" , 3333 )) ;
employees.add ( new Employee ( 4 , "FOUR" , 4444 )) ;
employees.add ( new Employee ( 5 , "FIVE" , 5555 )) ;
employees.add ( new Employee ( 6 , "SIX" , 6666 )) ;
stdContext.setVariable ( "emps" , employees ) ;
/**
* Employees having salary greater than 4000
*/
ExpressionParser parser = new SpelExpressionParser () ;
List<Employee> subSet = ( List<Employee> ) parser.parseExpression (
"#emps.?[salary > 4000]" ) .getValue ( stdContext ) ;
System.out.println ( subSet ) ;
/**
* Employees having salary less than 4000
*/
subSet = ( List<Employee> ) parser.parseExpression (
"#emps.?[salary < 4000]" ) .getValue ( stdContext ) ;
System.out.println ( subSet ) ;
}
}
It gives the following output,
[Employee[4, FOUR, 4444.0], Employee[5, FIVE, 5555.0], Employee[6, SIX, 6666.0]]
[Employee[1, ONE, 1111.0], Employee[2, TWO, 2222.0], Employee[3, THREE, 3333.0]]