JavaTechnology

How to Initialize a HashMap Inline in Java

In this tutorial you will learn different Ways of Creating HashMaps in Java. Including how to create and initialize Singleton, Empty, and Immutable maps.

The HashMaps are key value based unordered, unsorted collections. We often use HashMaps in Java and many a times we put hard coded values in it. Today, we will cover various ways of creating and initializing HashMaps. Also, we will learn to create Immutable, Singleton, and Empty maps.

HashMap using Constructor

Firstly, we will start with the most basic and traditional way to Initialize a HashMap.

Map<String, String> map = new HashMap<>();
map.put("color", "black");
map.put("drink", "coffee");
map.put("shape", "slim");

This type of HashMap creation is the most simple. Firstly you create an empty HashMap and then you have to put entries into it. This is a dynamic and mutable map. Hence you can add , update, or remove entries any number of times.

Anonymous Subclass to Create HashMap

Map<String, String> map = new HashMap<String, String>() {
    {
        put("color", "black");
        put("drink", "coffee");
        put("shape", "slim");
    }
};

This is a compact way of creating a Map. However, it is creating an extra sub-class and initializer block which is not good. Moreover, it also creates memory leak problems. Therefore, It is good to avoid using this technique.

Create Immutable HashMap

Map<String, String> map = new HashMap<>();
map.put("color", "black");
map.put("drink", "coffee");
map.put("shape", "slim");

Map<String, String> immutableMap = Collections.unmodifiableMap(map);

Creating an Immutable map using Collections.unmodifiableMap is a two step process. Firstly, you create a normal Map and then use it to create Immutable map. This will create two physically different maps, and certainly not good for large number of entries.

However, the immutable map, once created, cannot be modified. In other words, you cannot add, update or remove any entry from an immutable map. If you try to do so you will get java.lang.UnsupportedOperationException.

Singleton and Empty HashMaps using Collections

Below is a convenient way of creating a single entry Hashmap. It is also called as Singleton Map.

Example of Singleton Map.

Map<String, String> map = Collections.singletonMap("color", "black");

The Singleton maps are single entry and immutable in nature. In other words, once created, you can not add another entry or change any existing entry.

Similarly, you can create an Empty Map. As the name suggest it is a map with no entries.

Example of Empty Map.

Map<String, String> map = Collections.emptyMap();

An Empty map is also immutable that you can’t add any entry to the map.

Using Guava Library to Create HashMap

Using Google’s Guava Library, you can create and initialize maps inline.

Immutable Map using Google Guava

Map<String, String> map = ImmutableMap.of("color", "pink", "drink", "coffee", "shape", "slim");

However, it creates an Immutable map of n key/value pairs. The of function takes varargs and you can pass any number of entries inline.

There is a way to create a Mutable map using Google Guava.

Mutable Map using Google Guava

Map<String, String> immutableMap = ImmutableMap.of("color", "pink", "drink", "coffee", "shape", "slim");

Map<String, String> mutuableMap = Maps.newHashMap(immutableMap);

However, it creates two different maps. Firstly create an immutable map with the entries and then create a mutable map.

Using Streams to Create HashMap

Java 8 Streams have Collectors.toMap to create map from different things.

List to Map

List<User>  users = new ArrayList<>();
// .... populate users list
Map<String, Integer> nameToAge = users.stream().collect(Collectors.toMap(User::getName, User::getAge));

The above method takes two steps. First is to create a List or any other type of User collection. Second is to create stream and collect elements as a Map.

However, you can still create inline map using Collectors.toMap.

Map<String, Integer> inlineMap = Stream.of(
       new User(...),
       new User(...),
       ....)
.collect(Collectors.toMap(User::getName, User::getAge));

We have a separate tutorial on converting List to Map using Java Streams. Please visit to learn more.

Create HashMap using Java 9 Factory Methods

In Java 9, the Map interface comes with useful factory methods. Out of which, you can use Map.of method to create Maps inline.

Java 9 Map.of method

Map<String, String> immutableMap = Map.of("color", "black", "drink","coffee");

However, using this method you can create map of up to 10 entries only. The Map interface has 10 overloaded method, where first method accepts one key value pair and last one accepts 10 pairs.

static <K,V> Map<K,V> of (K k1, V v1);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2, K k3, V v3);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9);	
static <K,V> Map<K,V> of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10);	

On the other hand, if you want to create an inline map of infinite entries you can use Java 9 Map.ofEntries method.

Java 9 Map.ofEntries

Map<String, String> ofEntries = Map.ofEntries(
        Map.entry("color", "pink"),
        Map.entry("drink", "coffee")
);

This way your can add any number of entries to the map.

Important: The Java 9 Map interface methods creates Immutable maps only. However, you can use a simple HashMap constructor and pass the immutable map. This will create a completely new and mutable map.

Summary

In this tutorial, we learnt various ways of creating and initializing HashMaps in Java. To sum up, we started with a traditional way of creating maps. Also, we learnt creating maps using Anonymous Subclass, Java Collections, Stream Collectors, Google Guava, and Java 9 techniques. We also saw easy ways to create Immutable Maps, Singleton Maps, and Empty Maps.