To initialize a HashMap in Java you can use a below syntax:
1 2 3 4 5 6 |
HashMap<String, String> map = new HashMap<String, String>(){{ put("Apple", "Pie"); put("Chocolate", "Cookie"); }}; |
However, there are also other options. You can find a detailed description below
1. Static initializer
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private static final HashMap<String, String> staticMap = new HashMap<String,String>(); static{ staticMap.put("Apple", "Pie"); staticMap.put("Chocolate", "Cookie"); } public static void main(String args[]){ for(String key : staticMap.keySet()){ System.out.println(key + "\t" + staticMap.get(key)); } } |
As a prove, we can print all the values in main:
1 2 3 4 |
Apple Pie Chocolate Cookie |
2. “Double-brace” syntax
1 2 3 4 5 6 7 8 9 10 11 |
HashMap<String, String> map = new HashMap<String, String>(){{ put("Apple", "Pie"); put("Chocolate", "Cookie"); }}; for(String key : staticMap2.keySet()){ System.out.println(key + "\t" + staticMap2.get(key)); } |
This syntax (also introduced at the beginning of this post) is called double-brace. The first brace creates a new AnonymousInnerClass, the second declares and instance initializer block that is run when the anonymous inner class is instantiated. This kind of initializer is formally called an instance initializer. Sounds complicated, does it? If you want to use this option in your code you need to know how it works and beware of the invisible side effects.
The above code output is:
1 2 3 4 |
Apple Pie Chocolate Cookie |