java.util · java.base · since Java 1.2

HashMap

declaration
public class HashMap<K, V> extends AbstractMap<K, V>
        implements Map<K, V>, Cloneable, Serializable

The default Map: hashed buckets, O(1) operations, load factor 0.75, buckets treeify under collision pressure. Not thread-safe.

  • Resize (rehash) doubles the table — presize for bulk loads
  • One null key and null values allowed (unlike ConcurrentHashMap)

Key methods

HashMap(int initialCapacity, float loadFactor)Presize the table; capacity is rounded up to the next power of two, resize triggers once size exceeds capacity × loadFactor.
HashMap(Map<? extends K, ? extends V> m)Copy-construct from any map.
static <K,V> HashMap<K,V> newHashMap(int numMappings)Correctly presized factory accounting for load factor — the raw constructor takes table size, not entry count (Java 19+).

Example

Java
Map<String, List<String>> byDept = new HashMap<>();
for (Employee e : employees) {
    byDept.computeIfAbsent(e.getDept(), d -> new ArrayList<>()).add(e.getName());
}

Map<String, Integer> wordCounts = new HashMap<>();
for (String word : words) {
    wordCounts.merge(word, 1, Integer::sum);
}
computeIfAbsent builds a multimap in one line; merge turns counting into one too — no manual containsKey/get/put dance.