List Projection
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 projection operator (![projectionExpression] ).
It helps to evaluate a sub expression against the given collection and the result is a new collection.
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 ListProjectionTest {
/**
* @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 ) ;
ExpressionParser parser = new SpelExpressionParser () ;
List<String> proj = ( List<String> ) parser.parseExpression (
"#emps.![name]" ) .getValue ( stdContext ) ;
System.out.println ( proj ) ;
proj = ( List<String> ) parser.parseExpression (
"#emps.!['X-' + name.toLowerCase()]" ) .getValue ( stdContext ) ;
System.out.println ( proj ) ;
}
}
It gives the following output,
[ONE, TWO, THREE, FOUR, FIVE, SIX]
[X-one, X-two, X-three, X-four, X-five, X-six]