Jun 5, 2014

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.

Goals:

  1. minimal syntax
  2. no anonymous inner classes
  3. support different Key/Value types
  4. visually show the key=value pairing
  5. mimic Arrays.asList() syntax
  6. support unmodifiable
  7. 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.

About the Author

Neil Buesing profile.

Neil Buesing

VP - Streaming Technologies

Neil has more than twenty-five years of Object-Oriented development experience, with twenty years in Java/J2EE application development. He has successfully delivered in the role of an architect and as lead developer.

Over the past 2 years, he has lead up the Real-Time Data Practice at Object Partners. He is a Kafka Architect, Developer, and Advocate presenting at multiple Kafka Summits and Meetups.

One thought on “Inline initialization of Java Maps

  1. Corky says:

    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

    Version is my class

    Thanks

  2. Neil Buesing says:

    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

  3. Selena says:

    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

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blog Posts
Up to Spec: JavaScript Numeric Separators
Let's take a look at the proposal to add Numeric Separators to the JavaScript specification.
Using Conftest to Validate Configuration Files
Conftest is a utility within the Open Policy Agent ecosystem that helps simplify writing validation tests against configuration files. In a previous blog post, I wrote about using the Open Policy Agent utility directly to […]
SwiftGen with Image & Color Asset Catalogs
You might remember back in 2015 when iOS 9 was introduced, and we were finally given a way to manage all of our assets in one place with Asset Catalogs. A few years later, support […]
Tracking Original URL Through Authentication
If you read my other post about refreshing AWS tokens, then you probably have a use case for keeping track of the original requested resource while the user goes through authentication so you can route […]