Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

import java.util.Map;

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

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

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