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.
One thought on “Inline initialization of Java Maps”
I’m trying to use your MapUtils code. I’ve placed the following code inside my main.
final Map versionJdkMap = MapUtils.asMap(entry(“45.3”, 1), entry(“46.0”, 1));
It doesn’t compile, I get error The method entry(String, int) is undefined for the type
Version is my class
I’m guessing your missing the import static
import static com.objectpartners.buesing.util.MapUtils.entry;
You could add MapUtils. prefix to the ‘entry()’ method and then you wouldn’t need the MapUtils static import
Have you thought about publishing this as a jar to the maven central repo? I will, of course, download your code and add it to my project where I need something exactly like this, but it would be preferable to manage the dependency through Maven