HashMap
Overview
If ArrayList is a numbered list, `HashMap` is a dictionary. It stores data in Key-Value pairs. Instead of looking up a value by its index (0, 1, 2), you look it up by a unique Key (like a Username, SSN, or Product ID). HashMap is insanely fast. Regardless of whether the map has 10 items or 10 million items, finding a value by its key takes almost exactly the same amount of time (O(1) constant time).
Syntax
`put()`, `get()`, and `containsKey()` are the holy trinity of HashMap. They are the reason HashMap is the most heavily tested data structure in coding interviews.
// <KeyType, ValueType>
Map<String, Integer> inventory = new HashMap<>();
// 1. Adding Data (Put)
inventory.put("Apples", 50);
inventory.put("Bananas", 30);
inventory.put("Apples", 75); // Overwrites the old value! Keys MUST be unique.
// 2. Retrieving Data (Get)
int appleCount = inventory.get("Apples"); // 75
Integer orangeCount = inventory.get("Oranges"); // Returns null!
// 3. Checking Existence (Blazing Fast)
boolean hasBananas = inventory.containsKey("Bananas"); // true
// 4. Removing Data
inventory.remove("Bananas");Because HashMaps do not guarantee any specific order, you iterate over the `entrySet()`, which is a Set of all Key-Value pairs.
Map<String, String> capitals = new HashMap<>();
capitals.put("USA", "Washington D.C.");
capitals.put("Japan", "Tokyo");
// The most efficient way to loop through a Map
for (Map.Entry<String, String> entry : capitals.entrySet()) {
String country = entry.getKey();
String capital = entry.getValue();
System.out.println(country + " -> " + capital);
}
// Java 8+ Lambda way
capitals.forEach((country, capital) -> {
System.out.println(country + " -> " + capital);
});Common Pitfalls
- Using a custom object as a Key, but forgetting to override the `hashCode()` and `equals()` methods. The HashMap will completely lose your data because it won't know how to compare the keys.
- Calling `.get()` on a key that doesn't exist and trying to assign it to a primitive `int` or `double`. It will return `null`, causing an instant NullPointerException when unboxed.
Interview Tips
- This is the most asked data structure. Emphasize that it provides O(1) average time complexity for put and get operations.
Real-World Example
HashMaps are universally used for caching in backend systems to prevent hitting the database for frequently requested, unchanging data.
public class UserCache {
// Key: User ID, Value: User Object
private Map<Integer, User> cache = new HashMap<>();
public User getUser(int userId) {
// Fast O(1) lookup in memory
if (cache.containsKey(userId)) {
return cache.get(userId);
}
// Slow database hit
User user = db.fetchUserFromDatabase(userId);
cache.put(userId, user); // Store for next time
return user;
}
}