Initializing HashMaps in Java

How can I initialize a HashMap with some pre-defined entries?

In this article I’ll show you how you create a HashMap with values. Java doesn’t provide a method like Array.asList(). For initializing a map you have to implement something like that:

 //Old fashion way
 Map<Integer, String> oldFashion = new HashMap<Integer, String>() {{
     put(1, "one");
     put(2, "two");

So this is the double brace initialization idom. I don’t like this way. It’s not very readable, it’s creates a new class every time and may cause a memory leak. That’s may be okay for tests.

But as you know there isn’t just one way of doing it. With Java 8 you can solve my problem with a Lambda Expression.

 //Java 8 Lambda way
 Map<Integer, String> lambdaMap = Stream.of(
     new SimpleEntry<Integer, String>(1, "one"),
     new SimpleEntry<Integer, String>(10, "ten"))
         Collectors.toMap((se) -> se.getKey(), (se) -> se.getValue())

There are new methods added to java.util.Arrays to convert an array into a which can be used for summing, multiplying or collecting. Mmmh, I think that’s a lot of code for just initializing a Map with values.

Okay, let’s see what Guava can do for us.

 //Guava way
 ImmutableMap<Integer, String> guavaMap = ImmutableMap.of(
     1, "one",
     2, "two"

 //Guava way with builder
 ImmutableMap<Integer, String> guavaMap2 = ImmutableMap.<Integer, String> builder()
     .put(1, "one")
     .put(2, "two")
     .put(15, "fifteen")

Guava has a Factory Method ImmutableMap.of() which returns a immutable map containing our values. The Library has also a ImmutableMap.Builder<K,V>.build() method.

Lesson Learned

The Guava way is my favorite. It’s typed, safe, short and readable. If you are afraid of Guava, then consider the plain old way. The Java 8 Lambda Stream way is pretty ugly.

GitHub-Mark-32px Examples on Github