Home  >  Spring Core

Collection Selection Operator in Spring Expression Language (SpEL)

By Arvind Rai, October 26, 2013
Spring expression language provides Collection Selection Operator feature. It is a very powerful feature to filter a list on the basis of any criteria. It returns a new collection that will contain only those data which will follow the selection criteria. SpEL supports map and list both. In our example we have taken a list to represent Collection Selection Operator.

SpELTest.java
package com.concretepage;
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.concretepage.bean.StdList;
import com.concretepage.bean.Student;
public class SpELTest {
	public static void main(String[] args) {
		ExpressionParser parser = new SpelExpressionParser();
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("Ram",21));
		list.add(new Student("Shyam",20));
		list.add(new Student("Mahesh",21));
		list.add(new Student("Dinesh",23));
		
		StdList stdList = new StdList();
		stdList.setStdList(list);
		StandardEvaluationContext context = new StandardEvaluationContext(stdList);
		List<Student> subList = (List<Student>) 
			      parser.parseExpression("StdList.?[Age == 21]").getValue(context);
		
		for(Student s: subList){
		  System.out.println(s.getName() +"  "+s.getAge());	
		}
	}
}
 


Student.java
package com.concretepage.bean;
public class Student {
	private String name;
	private int age;
	public Student(String name, int age){
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
}
 


StdList.java
package com.concretepage.bean;
import java.util.ArrayList;
import java.util.List;
public class StdList {
	private List<Student> stdList = new ArrayList<Student>();
	public List<Student> getStdList() {
		return stdList;
	}
	public void setStdList(List<Student> stdList) {
		this.stdList = stdList;
	}
}
 
Output
Ram  21
Mahesh  21
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us