You can provide either Map.of or Map.ofEntries factory method, since Java 9, to the HashMap(Map) constructor to create and init a HashMap in one line

Apart from that, you can use put, Java 8+ putIfAbsent, putAll methods after the creation time to initialize a HashMap

Let's walk through this tutorial to explore them in more details

Initialize in one line with Java 9+ Map.of and Map.ofEntries

  • Provide either Map.of or Map.ofEntries factory method, since Java 9, to the HashMap(Map) constructor to create and init a HashMap in one line at the creation time
@Test
public void initInOneLineWithFactoryMethods() {  
    // create and initialize a HashMap from Java 9+ Map.of
    Map<String, Integer> map1 = new HashMap<>((Map.of("k1", 1, "k3", 2, "k2", 3)));
    assertThat(map1).hasSize(3);

    // create and initialize a HashMap from Java 9+ Map.ofEntries
    Map<String, Integer> map2 = new HashMap<>(Map.ofEntries(Map.entry("k4", 4), Map.entry("k5", 5)));
    assertThat(map2).hasSize(2);
}
  • Both Map.of and Map.ofEntries will throw IllegalArgumentException if there are any duplicate keys and NullPointerException if any entry, key, value is null

Initialize in one line from an existing Map

  • Provide an existing Map to the HashMap(Map) constructor to create and init a HashMap in one line
@Test
public void initInOneLineFromAnExistingMap() {  
    Map<String, Integer> map1 = new HashMap<>(Map.ofEntries(Map.entry("k4", 4), Map.entry("k5", 5)));

    // create and initialize from an existing map
    Map<String, Integer> map2 = new HashMap<>(map1);
    assertThat(map2).hasSize(2);
}

Initialize after the creation time with put, Java 8+ putIfAbsent, putAll

  • The put(key, value) method is used for adding key-value mapping entry into a HashMap

    null key and null values are allowed

    The value of a duplicate key will be overridden

@Test
public void initializeWithPut() {  
    // Create a new HashMap
    Map<String, Integer> map = new HashMap<>();

    // Add elements to HashMap
    map.put("k1", 1);
    map.put("k2", 2);
    map.put("k3", 3);

    // Can add null key and null values
    map.put(null, 4);
    map.put("k4", null);

    // Value of duplicate key will be overridden
    map.put("k1", 10);
    assertThat(map).hasSize(5);

    // The output ordering will be vary as Map is not reserved the insertion order
    System.out.println(map);
}
  • Java 8+ introduces putIfAbsent to ignore duplicate key when adding entry into a HashMap
@Test
public void initializeWithPutIfAbsent() {  
    // Create a new HashMap
    Map<String, Integer> map = new HashMap<>();

    // Add elements to HashMap
    map.putIfAbsent("k1", 1);
    map.putIfAbsent("k2", 2);
    map.putIfAbsent("k3", 3);

    // Can add null key and value
    map.putIfAbsent(null, 4);
    map.putIfAbsent("k4", null);

    // Duplicate key will be ignored
    map.putIfAbsent("k1", 10);
    assertThat(map).hasSize(5);

    // The output ordering will be vary as Map is not reserved the insertion order
    System.out.println(map);
}
  • The putAll(Map) copies all the mappings from the specified map

    NullPointerException will be thrown if the specified map is null

@Test
public void initializeWithPutAll() {  
    // Create a new HashMap
    Map<String, Integer> map1 = new HashMap<>();

    // Add all from Java 9+ Map.of
    map1.putAll(Map.of("k1", 1, "k3", 2, "k2", 3));

    // Add all from Java 9+ Map.ofEntries
    map1.putAll(Map.ofEntries(Map.entry("k4", 4), Map.entry("k5", 5)));

    assertThat(map1).hasSize(5);

    // Add all from an existing map
    Map<String, Integer> map2 = new HashMap<>();
    map2.putAll(Map.copyOf(map1));
    assertThat(map2).hasSize(5);
}

Double brace initialization should not be used in practice

  • Double brace initialization can cause a memory leak as it creates anonymous classes with an hidden reference to the owner instance object
@Test
public void initializeWithDoubleBrace() {  
    // Create a new HashMap
    Map<String, Integer> map = new HashMap<>(){{
        put("k1", 1);
        put("k3", 2);
        put("k2", 3);
    }};

    assertThat(map).hasSize(3);
}

Conclusion

In this tutorial, we learned some ways to create and initialize a HashMap in Java. You can find the full source code as below