Projecting maps in SpEL

In this post under SpEL, I will show with example how to project a specific field (key or value field) of a map.

Below is the complete main code showing how to do it.

Main class

1  package spel.package14;
2  
3  import org.springframework.beans.factory.annotation.Value;
4  import org.springframework.context.ApplicationContext;
5  import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6  import org.springframework.context.annotation.Bean;
7  import org.springframework.context.annotation.ComponentScan;
8  import org.springframework.context.annotation.Configuration;
9  
10 import java.util.HashMap;
11 import java.util.List;
12 import java.util.Map;
13 
14 @Configuration
15 @ComponentScan(basePackages = "spel.package14")
16 public class Example14 {
17     @Value("#{maps.![key * 2]}")
18     private List<Integer> integerList;
19 
20     @Bean("maps")
21     public Map<Integer, String> getMaps() {
22         Map<Integer, String> map = new HashMap<>(0);
23         map.put(100, "Hundred");
24         map.put(200, "Two Hundred");
25         map.put(300, "Three Hundred");
26         map.put(400, "Four Hundred");
27         map.put(500, "Five Hundred");
28 
29         return map;
30     }
31 
32     public static void main(String[] args) {
33         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example14.class);
34         Example14 example14 = applicationContext.getBean(Example14.class);
35         for(Integer value : example14.integerList) {
36             System.out.println(value);
37         }
38     }
39 }

In the above code, “getMaps” method create a bean of type “Map” with key of type “Integer” and value of type “String”.

Now my requirement is to extract only the key field from the map, multiply it with 2 and put it in a new collection.

To achieve the above requirement, I use the SpEL shown at line 17.

The syntax to extract key or value field of a map is similar to syntax used to extract fields from a collection of objects as shown below

mapName.![field to be extracted]

The syntax involves map name followed by “.!” operator and the field (i.e., key or value) to be extracted within square bracket.

We print the resulting collection to console at line 35.

In this way we can project key or value field of a map.

Leave a comment