I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:
hashMap.put(\"One\", new Integer(1)); // add
Here's a simple class that will accomplish what you want
import java.util.HashMap;
public class QuickHash extends HashMap<String,String> {
public QuickHash(String...KeyValuePairs) {
super(KeyValuePairs.length/2);
for(int i=0;i<KeyValuePairs.length;i+=2)
put(KeyValuePairs[i], KeyValuePairs[i+1]);
}
}
And then to use it
Map<String, String> Foo=QuickHash(
"a", "1",
"b", "2"
);
This yields {a:1, b:2}
Since Java 9, it is possible to use Map.of(...), like so:
Map<String, Integer> immutableMap = Map.of("One", 1,
"Two", 2,
"Three", 3);
This map is immutable. If you want the map to be mutable, you have to add:
Map<String, Integer> hashMap = new HashMap<>(immutableMap);
If you can't use Java 9, you're stuck with writing a similar helper method yourself or using a third-party library (like Guava) to add that functionality for you.
You can use the Double Brace Initialization as shown below:
Map<String, Integer> hashMap = new HashMap<String, Integer>()
{{
put("One", 1);
put("Two", 2);
put("Three", 3);
}};
As a piece of warning, please refer to the thread Efficiency of Java “Double Brace Initialization" for the performance implications that it might have.