In this post I will explain with example how to filter maps in SpEL expression.
For our example we will use the below main class
Main class
package spel.package12;
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.HashMap;
import java.util.Map;
@Configuration
@ComponentScan(basePackages = "spel.package12")
public class Example12 {
@Value("#{maps.?[key >= 300]}")
private Map<Integer, String> integerStringMap;
@Bean("maps")
public Map<Integer, String> getMaps() {
Map<Integer, String> map = new HashMap<>(0);
map.put(100, "Hundred");
map.put(200, "Two Hundred");
map.put(300, "Three Hundred");
map.put(400, "Four Hundred");
map.put(500, "Five Hundred");
return map;
}
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example12.class);
Example12 example12 = applicationContext.getBean(Example12.class);
for(Map.Entry<Integer, String> entry : example12.integerStringMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
In the above code from line 20 to 28, we create a bean of type Map named “maps”.
In this map the key is of type Integer and value is of type String.
In the above code, at line 16 we have SpEL expression.
In this expression, I access the bean “maps” followed by “.?” operator and the conditional expression within the square bracket.
In the SpEL expression, we can access the key of map using “key” keyword and value of the map using “value” keyword.
In our SpEL expression, we are filtering maps and returning a new map whose key is greather than 300. This new map is assigned to variable “integerStringMap”.
In this way we can filter maps in SpEL.
Below is the output
Output
400:Four Hundred
500:Five Hundred
300:Three Hundred