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:
def map = [name: ‘Gromit’, likes: ‘cheese’, id: 1234].
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.*
Jump to source
*This leads, me anyway, to wondering how do you test compile only concerns, like generics? Sure, compile errors are thrown if you try to use Generics type-safe code incorrectly. But, how do you know your generics code is meeting the requirements, or that future maintenance would not still enforce the requirements?
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
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License