Pages

Friday, August 10, 2012

Dynamic initialization of HashMap using double braces

Often we have to work with data structures like: Maps, Arrays,Sets...
And many times it is just more comfortable to initialize them dynamically.

In the following example i use double brace initialization technique to dynamically initialize a map that uses a constant as a key and a List as a value. When we want to initialize this types of structures in a dynamical way, this approach is probably the most comfortable and easy.


1:  new HashMap<ProductCategories, List<Products>>() {  
2:                 {  
3:                      put(ProductCategories.DAIRY_PRODUCTS,  
4:                                new ArrayList<Products>() {  
5:                                     {  
6:                                          add(Products.CHEESE);  
7:                                          add(Products.SOUR_CREAM);  
8:                                          add(Products.YOGURTH);  
9:                                     }  
10:                                 }  
11:                      );  
12:                      put(ProductCategories.MEAT,   
13:                                new ArrayList<Products>() {  
14:                                     {  
15:                                          add(Products.BEEF);  
16:                                          add(Products.CHICKEN);  
17:                                          add(Products.TURKEY);  
18:                                     }  
19:                                }  
20:                      );  
21:                      put(ProductCategories.VEGETABLES,   
22:                                new ArrayList<Products>() {  
23:                                     {  
24:                                          add(Products.TOMATO);  
25:                                          add(Products.ONION);  
26:                                          add(Products.CAGABE);  
27:                                     }  
28:                                }  
29:                      );  
30:                 }  
31:            };  

No comments:

Post a Comment

Share with your friends