Inline initialization of Java Maps
Inline initialization of maps in Java has been a sign of weakness in the Java language. This approach has given me the most concise way to initialize maps, while meeting all of my goals.
- minimal syntax
- no anonymous inner classes
- support different Key/Value types
- visually show the key=value pairing
- mimic Arrays.asList() syntax
- support unmodifiable
- support any Map implementation (in my case, HashMap and LinkedHashMap)
I have found articles and 3rd part libraries that come close, and my be the idea choice for you. However, none met all of the goals above, so I kept looking for a new solution (I know, goals like ‘minimal syntax’ is up for debate, if I actually achieved that).
If you include MapUtils, which is less than 50 lines of code, and you statically import one of the methods, MapUtils.entry() you can initialize a Map as follows:
Map<String,Integer> map = MapUtils.asMap(entry(“A”, 1), entry(“B”, 2), entry(“C”, 3), entry(“D”, 4));
Map<String,Integer> map = MapUtils.asUnmodifiableMap(entry(“A”, 1), entry(“B”, 2), entry(“C”, 3), entry(“D”, 4));
Here is the source code for MapUtils.java
This is a simple unit test showing various ways to initialize inline maps; compare and see what technique you like best.
For completeness sake, here is a unit test MapUtilsTest.java
Now, maybe someday, Java will learn from Groovy and add these higher level data structure concepts to the language. While I can appreciate a language that tries not to embedded higher-level object concepts into the core, Java has already crossed this line with the introduction of Java5 for-loop syntax. Also, from Java’s beginning, making String objects from character arrays. In the meantime we all search the web and find various techniques to try to reduce the amount of Java code we write. Maybe someday I can work on an application server that allows me to utilize Java 8 and I can finally have my lambda expressions; or at least Java’s implementation and I can start getting rid of more of the boiler plate code I’m forced to write. For now, I will just be happy with my inlined initialized Maps.