Convenient entry of initialized static hash table

Is there a way to write a static final Hashtable in java in key value pairs in the same way that you can initialize an array of strings conveniently, like:

String [] foo = {"A","AB"}; 

Basically, I mean that you do not need to write the words β€œput” for the key: value pairs, but instead, there might be something like:

 Hashtable<String, String> foo = {"JJ":"222","KK":"222"} 

which IMO looks more elegant.

(I know that initialization should be in a static block. I leave it now)

+7
source share
4 answers

No, there are no literals in Java, but they have array literals.

 static final Map<String, String> map; static { map = new HashMap<String, String>(); String[][] pairs = { {"foo", "bar"}, {"x", "y"} }; for (String[] pair : pairs) { map.put(pair[0], pair[1]); } } 

Of course, this does not add anything to direct copying and pasting put , and it will not work if your key and value types do not match.

+7
source

An anonymous inner class will give you double initialization, which is useful in some cases:

 static final Map<String, String> map = new HashMap<String, String>() {{ put("foo", "bar"); put("x", "y"); }}; 

Anyway @ michael667's answer is probably the best

+8
source

You can use guava ImmutableMap :

 map = ImmutableMap.of(key1, value1, key2, value2); 
+7
source

No, you are looking for something like C # collection initializers that do not currently exist in Java.

You can use an anonymous class to save a little typing, but you still have to write put .

-one
source

All Articles