Map 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.HashMap;
import java.util.List;
import java.util.Map;
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 MapProjectionTest {
/**
* @param args
*/
public static void main ( String [] args ) {
StandardEvaluationContext stdContext = new StandardEvaluationContext () ;
Map<Integer, Employee> employees = new HashMap<Integer, Employee> () ;
employees.put ( 1 , new Employee ( 1 , "ONE" , 1111 )) ;
employees.put ( 2 , new Employee ( 2 , "TWO" , 2222 )) ;
employees.put ( 3 , new Employee ( 3 , "THREE" , 3333 )) ;
employees.put ( 4 , new Employee ( 4 , "FOUR" , 4444 )) ;
employees.put ( 5 , new Employee ( 5 , "FIVE" , 5555 )) ;
employees.put ( 6 , new Employee ( 6 , "SIX" , 6666 )) ;
stdContext.setVariable ( "empMap" , employees ) ;
ExpressionParser parser = new SpelExpressionParser () ;
List<String> proj = ( List<String> ) parser.parseExpression (
"#empMap.![value.name]" ) .getValue ( stdContext ) ;
System.out.println ( proj ) ;
proj = ( List<String> ) parser.parseExpression (
"#empMap.![(key*10) + '-' + value.name.toLowerCase()]" ) .getValue ( stdContext ) ;
System.out.println ( proj ) ;
}
}
It gives the following output,
[ONE, TWO, THREE, FOUR, FIVE, SIX]
[10-one, 20-two, 30-three, 40-four, 50-five, 60-six]