You can create and initialize a HashMap by using its constructors, util methods of Collection class or Map.of(), Map.ofEntries() and Map.copyOf() of Java 9+

Using HashMap's constructors

  • Create a new empty HashMap
Map<String, Integer> map = new HashMap<>();  
  • Create and init a new HashMap with the same mappings as the specified map
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
System.out.println(map); // {k1=1}

Map<String, Integer> map2 = new HashMap<>(map);  
System.out.println(map2); // {k1=1}  
  • Create and init a map in one line with double brace initialization (should not be used)
Map<String, Integer> map = new HashMap<>(){{  
   put("k1", 1);
   put("k2", 2);
}};

Double brace initialization can lead to memory leaks as it creates an anonymous class with a reference to the owner object

  • Create and init a map in multiple lines
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", 2);  


Using Collections class

  • Create a new empty unmodifiable map with Collections.emptyMap()
Map<String, Integer> immutableMap = Collections.emptyMap();  
  • Create and init a single key-value unmodifiable map in one line with Collections.singletonMap(K key, V value)
Map<String, Integer> immutableMap = Collections.singletonMap("k1", 1);  


Using Map.of, Map.ofEntries and Map.copyOf with Java 9+

Using Map.of, Map.ofEntries and Map.copyOf factory methods to create and init an unmodifiable map in one line.

UnsupportedOperationException will be thrown if attempting to add, remove or update keys and values

NullPointerException will be thrown if attempting to create with null keys or values

IllegalArgumentException will be thrown if attempting to create with duplicate keys

  • with Map.of(...)
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
  • with Map.ofEntries(...)
Map<String, Integer> immutableMap = Map.ofEntries(Map.entry("k1", 1), Map.entry("k2", 2));  
  • with Map.copyOf(...)
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", 2);

Map<String, Integer> immutableMap = Map.copyOf(map);  
System.out.println(immutableMap); // {k2=2, k1=1}