HashMap
HashMap is Java's default Map implementation. It stores key-value pairs in a hash table, giving average O(1) time for get, put, remove and containsKey.
Usage
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> scores = new HashMap<>();
scores.put("Ada", 95);
scores.put("Grace", 98);
scores.get("Ada"); // 95
scores.getOrDefault("Unknown", 0); // 0
scores.putIfAbsent("Linus", 90);
scores.computeIfAbsent("Ken", k -> 0);
scores.merge("Ada", 5, Integer::sum); // 95 + 5 = 100
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
equals + hashCode
Keys must have consistent hashCode() and equals() methods. If you mutate a key after inserting it (changing its hash), you'll lose it in the map.
Not ordered, not thread-safe
- Iteration order is unspecified and can change between JVM versions.
- For insertion-order iteration: use
LinkedHashMap. - For sorted-by-key iteration: use
TreeMap. - For concurrent access: use
ConcurrentHashMap(notHashtable— that's the legacy version).
Hash collision handling
Since Java 8, HashMap uses a hybrid of linked lists and balanced trees per bucket. When a bucket accumulates too many collisions, it converts to a tree to keep worst-case lookup at O(log n) instead of O(n). Rarely relevant unless you intentionally induce collisions.