Map 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 map entry (Map.Entry).
package com.bethecoder.tutorials.spring3.tests.spel;
import java.util.HashMap;
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 MapSelectionTest {
/**
* @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 ) ;
/**
* Employees having salary greater than 4000
*/
ExpressionParser parser = new SpelExpressionParser () ;
Map<Integer, Employee> subSet = ( Map<Integer, Employee> ) parser.parseExpression (
"#empMap.?[value.salary > 4000]" ) .getValue ( stdContext ) ;
System.out.println ( subSet ) ;
/**
* Employees having salary less than 4000
*/
subSet = ( Map<Integer, Employee> ) parser.parseExpression (
"#empMap.?[value.salary < 4000]" ) .getValue ( stdContext ) ;
System.out.println ( subSet ) ;
}
}
It gives the following output,
{4=Employee[4, FOUR, 4444.0], 5=Employee[5, FIVE, 5555.0], 6=Employee[6, SIX, 6666.0]}
{1=Employee[1, ONE, 1111.0], 2=Employee[2, TWO, 2222.0], 3=Employee[3, THREE, 3333.0]}