Filtering collections in SpEL

In this post, I will explain with example how to filter collections in SpEL.

For our example we will use the below model class

Student

package spel.package11;

public class Employee {
    private int id;
    private String name;
    private int salary;

    public Employee(int id, String name, int salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    //Removed getter and setter for brevity
}

Below is the complete main code for your reference.

Main class

package spel.package11;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
@ComponentScan(basePackages = "spel.package11")
public class Example11 {
    @Value("#{employees.?[salary > 500]}")
    private List<Employee> filteredEmployeeList;

    @Bean("employees")
    public List<Employee> getEmployees() {
        List<Employee> list = new ArrayList<>(0);
        for(int i = 1; i <= 10; i++) {
            Employee employee = new Employee(i, "name" + i, (i * 100));
            list.add(employee);
        }

        return list;
    }

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example11.class);
        Example11 example11 = applicationContext.getBean(Example11.class);
        for(Employee employee : example11.filteredEmployeeList) {
            System.out.println(employee.getSalary());
        }
    }
}

In the above program, from line 20 to 28, I created a bean of type List named “employees”.

This “employees” list contains a list of 10 “Employee” objects.

In the above code, at line 16, I use the “employees” bean in SpEL expression.

In the expression we are accessing the bean by bean name, followed by “.?” operator and then the conditional expression within the square bracket.

This SpEL expression filters the “employees” list and assign the resulting collection to the instance variable “filteredEmployeeList”

This SpEL expression creates a new collection which contains employee objects whose salary is greater then 500 and assign that collection to instance variable “filteredEmployeeList”.

In this way we can filter collections in SpEL expression.

Below is the output

Output

600
700
800
900
1000

Leave a comment