This is a common task, and there are many good and bad solutions out there. Java 8 even has a “Supplier” that can assist with inline map initializations.
Unfortunately, Java does not have a simple method like that found in the Groovy language. A map in Groovy is:
I implemented a builder in Java 7 that is just simple syntax sugar. This is before I found Per-Åke Minborg’s great blog post Java 8, Initializing Maps in the Smartest Way on the topic, or the others found online. Perhaps I was using the wrong search. Hmm.
Using my version without all the Generics details:
Map codes = InitMap.with(new HashMap())
.put(“xyz”,”321″).put(“abc”,”362″).toMap();
Alternatively, you can create a Map instance and use the builder, no need to invoke toMap():
Map<String,String> map = new HashMap<>();
InitMap.with(map).put(“xyz”,”321″).put(“abc”,”362″);
How does it work? InitMap is just a “partial” Decorator. When you create the InitMap object the Map parameter is stored in a field. Then when you “put” key/values, they becomes a ‘put’ to the hidden map. This allow you to chain the ‘put’s. When your done adding entries, you invoke toMap() to get the actual Map instance. The simplest thing that works.
Not too sure about the Generics stuff. Generics are like a loose thread on a coat; if you keep pulling on it, soon you’ll have no coat.*
Links
- Java 8, Initializing Maps in the Smartest Way
- Inline initialization of Java Maps
- Java Reflection Method Invoke Using Fluent Interface
Footnotes
Hmm. Only thing I can think of is you have to write unit test that invoke a Javac compiler on strings of source code.
- Java 8, but not the new JDK features.
- Eclipse Mars for development
Listing 1, InitMap and tests implementation, full source Gist