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 at the creation time

To initialize a HashMap after the creation time, you can use put, Java 8+ putIfAbsent, putAll methods

Initial capacity (the number of a hash table buckets) and load factor are important settings to the HashMap performance as they can reduce the number of resize and rehash operations

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 an 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 a 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);
}

Initial capacity and load factor

  • When you create and initialize a new HashMap by using the default constructor HashMap(), the initial capacity and load factor are set to 16 and 0.75 respectively

    You can also provide their custom values by using HashMap(initialCapcity) and HashMap(initialCapcity, loadFactor) constructors

@Test
public void initializeWithInitialCapacityAndLoadFactor() {  
    // init with 16 and 0.75 as default initial capacity and default load factor
    Map<String, Integer> map1 = new HashMap<>();

    int initialCapacity = 2;
    // init with 2 and 0.75 as initial capacity and default load factor
    Map<String, Integer> map2 = new HashMap<>(initialCapacity);

    float loadFactor = 1;
    // init with 16 and 1 as default initial capacity and load factor
    Map<String, Integer> map3 = new HashMap<>(initialCapacity, loadFactor);
}

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


Share to social

Van N.

Van N. is a software engineer, creator of HelloKoding. He loves coding, blogging, and traveling. You may find him on GitHub and LinkedIn