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.
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())
Alternatively, you can create a Map instance and use the builder, no need to invoke toMap():
Map<String,String> map = new HashMap<>();
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.*
- Java 8, Initializing Maps in the Smartest Way
- Inline initialization of Java Maps
- Java Reflection Method Invoke Using Fluent Interface
- Java 8, but not the new JDK features.
- Eclipse Mars for development
Listing 1, InitMap and tests implementation, full source Gist