HashMap: Key-Value Pairs
A HashMap is a collection that stores data in Key-Value pairs. Think of it like a real dictionary: the "word" is the Key, and the "definition" is the Value. You use the unique key to look up the value instantly.
1. Key Characteristics
- Unique Keys: You cannot have duplicate keys. If you add a new value with an existing key, the old value is overwritten.
- Fast Lookup: It is extremely fast at finding values if you know the key (O(1) average time complexity).
- Unordered: It does not maintain the order in which items are added.
- Wrapper Classes: Like
ArrayList, it only stores objects. UseIntegerinstead ofint.
2. Basic Operations
| Action | Method | Example |
|---|---|---|
| Add/Update | .put(key, value) |
map.put("c0der", 100); |
| Access | .get(key) |
Integer score = map.get("c0der"); |
| Remove | .remove(key) |
map.remove("c0der"); |
| Check Key | .containsKey(key) |
map.containsKey("admin"); |
| Size | .size() |
map.size(); |
💻 Full Practical Example: User Database
Copy this to see how to manage a mock database of user scores:
import java.util.HashMap;
public class GameData {
public static void main(String[] args) {
// Syntax: HashMap<KeyType, ValueType>
HashMap<String, Integer> scores = new HashMap<>();
// 1. Adding data
scores.put("Amine", 95);
scores.put("Sarah", 88);
scores.put("Guest_123", 40);
// 2. Updating a value (Amine gets a bonus)
scores.put("Amine", 100);
// 3. Accessing data
if (scores.containsKey("Sarah")) {
System.out.println("Sarah's Score: " + scores.get("Sarah"));
}
// 4. Iterating through the map
System.out.println("\n--- Full Leaderboard ---");
for (String name : scores.keySet()) {
System.out.println(name + ": " + scores.get(name));
}
}
}
3. How it Works (Hashing)
When you put a key into a HashMap, Java runs a "Hash Function" on that key to calculate an index (a bucket). It stores the pair in that bucket. When you ask for the key again, it runs the same function to jump directly to the right bucket. This is why it stays fast even with millions of items!
💡 Challenge: The Inventory Tracker
- Create a
HashMap<String, Double>calledmenu. - Add three items (e.g., "Coffee" -> 2.50, "Tea" -> 2.00, "Cake" -> 4.75).
- Print the price of "Tea".
- Remove "Cake" from the menu.
- Print the entire menu to show the remaining items and their prices.