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:

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

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.

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

There are new methods added to java.util.Arrays to convert an array into a java.util.stream.Stream 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.

[code]
//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")
.build();
[/code]

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

Consent Management Platform von Real Cookie Banner