Ben Chuanlong Du's Blog

It is never too late to learn.

Directly Initialize a Hashmap in Java

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

The following code snippet in Java 9+ initialize an immutable HashMap with up to 10 elements.

In [1]:
import java.util.Map;

Map<String, String> m1 = Map.of(
    "a", "b",
    "c", "d"
);
In [2]:
System.out.println(m1);
{c=d, a=b}

The following code snippet in Java 9+ initialize an immutable HashMap with arbitrary number of elements.

In [3]:
import java.util.Map;
import static java.util.Map.entry;    
Map<String, String> m2 = Map.ofEntries(
    entry("a", "b"),
    entry("c", "d")
);
In [4]:
System.out.println(m2);
{c=d, a=b}
In [ ]:

Comments