How to Initialize a HashMap Inline in Java

Examples of creating and adding the key-value pairs to a Java HashMap inline.

Overview

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

Creating a Simple HashMap

The most basic way of creating a HashMap instance and adding a few elements is to use a constructor to create an empty HashMap and then add elements one by one.
Example of initializing a simple HashMap.

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

Although this is a two-step operation, the HashMap we created is mutable; thus, we can add, remove, or modify elements.

Creating a HashMap using Anonymous Subclass

We can use an anonymous subclass to instantiate and initialize a Java HashMap in the same line.

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

This way is not recommended for initializing a Java HashMap as it has a lot of overhead and potential memory leak issues.

Creating an Immutable HashMap

The Java Collections class offers the unmodifiableMap() method that creates an immutable HashMap containing the elements from the given Map.
Example of initializing an immutable Java 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);Code language: Java (java)

Using the Collections unmodifiableMap() method, we can create an immutable copy of an existing Java HashMap. As the resulting HashMap is immutable, we cannot add, update, or remove elements.

Creating a Singleton HashMap

The singletonMap() method of the Java Collections class creates an immutable HashMap containing the given key-value pair.
Example of creating a singleton HashMap.

Map<String, String> map = 
    Collections.singletonMap("color", "black");Code language: Java (java)

A singleton HashMap contains one and only one key-value pair. As it is immutable, we cannot modify its contents.

Creating an Empty HashMap

The emptyMap() method of the Java Collections class creates an empty HashMap instance.
Example of creating an empty Java HashMap.

Map<String, String> map = Collections.emptyMap();Code language: Java (java)

Please note that the resulting HashMap is immutable. Thus, it remains empty forever.

Creating a HashMap using Google Guava

Google’s Guava Library provides several useful abstractions and utility methods to work with the Java Collections framework. Let’s see how the Guava Library helps to initialize mutable and immutable HashMap instances inline.

Immutable HashMap using Guava

Guava’s ImmutableMap class implements Java Map, representing an immutable HashMap. The class provides the of() method, a factory method that creates an immutable Java HashMap containing the given key-value pairs.
Example of initializing an immutable Java HashMap using Google Guava.

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

Mutable HashMap using Guava

The Maps class of Guava is a static utility class with useful abstractions. The newHashMap() method of the Maps class returns a mutable HashMap instance containing all the elements of the given Map.
Example of initializing a mutable Java HashMap using Google Guava.

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

Map<String, String> mutuableMap = Maps.newHashMap(immutableMap);Code language: Java (java)

Although we provide an immutable Map, the newHashMap() method always returns a mutable HashMap.

Creating a HashMap using Stream Collectors

The Java Collectors class provide a collector abstraction that collects the Stream elements and forms a Java HashMap.

Example of initializing a Java HashMap using Stream Collectors.

List<String> colors = List.of("Pink", "Red", "Black");
Map<String, String> map = colors.stream()
    .collect(Collectors
        .toMap(String::toUpperCase, String::toLowerCase));
System.out.println(map);

//prints:
//{RED=red, PINK=pink, BLACK=black}Code language: Java (java)

We have a separate tutorial on converting List to Map using Java Streams.

Creating a HashMap using Factory Method

Java 9 introduced factory methods to the Map interface that we can use to do inline initialization of Java HashMap instances.

Using the Factory Method of()

The of() method of the Map interface accepts key-value pairs in the form of varargs and returns a new immutable HashMap containing the elements.
Example of initializing Java HashMap inline using factory methods.

Map<String, String> immutableMap = 
    Map.of("color", "black", "drink","coffee");Code language: Java (java)

Please note that the Map interface has ten overloaded versions of the of() method.

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);	
Code language: Java (java)

This is why we can only use the factory method of() to create an inline HashMap of up to ten key-value pairs.

Using the Factory Method ofEntries()

Alternatively, the ofEntries() method of the Map method accepts n key-value pairs and can initialize a HashMap of infinite elements.

Example of initializing inline Java HashMap using Map ofEntries() method.

Map<String, String> ofEntries = Map.ofEntries(
        Map.entry("color", "pink"),
        Map.entry("drink", "coffee")
);Code language: Java (java)

Summary

This article demonstrated different ways of creating mutable and immutable Java HashMap instances and adding key-value pairs in the same line. We used Java Map factory methods, Collections class, and the Guava Library to initialize the Maps inline.

Please refer to our GitHub Repository for the complete source code of the examples.