Collections in SpEL

You can reference a single member of a collection in SpEL, just like in Java. But SpEL also has the power to select members of a collection based on the values of their properties. It can also extract properties out of the collection members into a new collection.

Accessing Collection Members

The most basic thing we could do here is extract a single element out of the list.

Employee emp = (Employee) parser.parseExpression(
	        "#emps[0]").getValue(context);

Collection Selection

Selection is a powerful expression language feature that allows you to transform some source collection into another by selecting from its entries.

Selection uses the syntax ?[selectionExpression]. This will filter the collection and return a new collection containing a subset of the original elements. Selection is possible upon both lists and maps.

List<Employee> subSetEmployee = (List<Employee>) parser.parseExpression(
	        "#emps.?[salary > 200000]").getValue(context);

Map<Integer, Employee> subSetEmployee = (Map<Integer, Employee>) parser.parseExpression(
	        "#emps.?[value.salary > 200000]").getValue(context);

SpEL also offers two other selection operators, .^[] and .$[], for selecting the first and last matching items (respectively) from a collection.

Employee emp = (Employee) parser.parseExpression(
	        "#emps.^[salary > 200000]").getValue(context);

Map<Integer, Employee> subSetEmployee = (Map<Integer, Employee>) parser.parseExpression(
	        "#emps.^[value.salary > 200000]").getValue(context);

Collection Projection

Collection projection is a fascinating feature of SpEL. It essentially takes as input objects and returns a cross section of those objects in the form of their properties after having operated on their properties. The syntax for projection is ![projectionExpression]. For example: we have list of employees, but we want only their names.

List<String> subSetEmployee = (List<String>) parser.parseExpression(
	        "#emps.![name]").getValue(context);

List<String> subSetEmployee = (List<String>) parser.parseExpression(
		        "#emps.![value.name]").getValue(context);

You can download the source code of this example here.

, , ,

No comments yet.

Leave a Reply