Java HashMap
Learn about Java HashMap. Understand how to store data in Key-Value pairs, access elements efficiently, and iterate through maps.
A HashMap store items in Key/Value pairs, and you can access them by an index of another type (e.g. a String).
Think of a Dictionary 📖.
- Key: The word (e.g., "Apple").
- Value: The definition (e.g., "A red fruit").
- You look up the definition using the word.
graph LR
K1[Key: England] -->|Hash Function| B1[Value: London]
K2[Key: Germany] -->|Hash Function| B2[Value: Berlin]
K3[Key: Norway] -->|Hash Function| B3[Value: Oslo]
style K1 fill:#e1f5fe,stroke:#01579b
style K2 fill:#e1f5fe,stroke:#01579b
style K3 fill:#e1f5fe,stroke:#01579b
style B1 fill:#fff9c4,stroke:#fbc02d
style B2 fill:#fff9c4,stroke:#fbc02d
style B3 fill:#fff9c4,stroke:#fbc02dVisualizing Key-Value Mapping
How does it handle collisions? 🤔 If two keys have the same hash code (Collision), they are stored in the same "bucket" (usually a LinkedList or Balanced Tree). Java handles this automatically!
Creating a HashMap
import java.util.HashMap;
// Key: String, Value: String
HashMap<String, String> capitalCities = new HashMap<String, String>();Common Operations
1. Add Items
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");2. Access Items
System.out.println(capitalCities.get("England")); // Output: London3. Remove Items
capitalCities.remove("England");
capitalCities.clear(); // Removes ALL items4. Map Size
System.out.println(capitalCities.size());Loop Through a HashMap
You can loop through keys or values.
// Print keys
for (String i : capitalCities.keySet()) {
System.out.println(i);
}
// Print values
for (String i : capitalCities.values()) {
System.out.println(i);
}
// Print keys and values
for (String i : capitalCities.keySet()) {
System.out.println("key: " + i + " value: " + capitalCities.get(i));
}Tip 💡: Keys in a HashMap must be unique. If you try to put a key that already exists, it will overwrite the old value!
Other Types
Keys and values can be of different types.
// Key: String (Name), Value: Integer (Age)
HashMap<String, Integer> people = new HashMap<String, Integer>();
people.put("John", 32);
people.put("Steve", 30);
people.put("Angie", 33);What happens if you insert a duplicate key into a HashMap?
Note : Java is a statically-typed language. It means that all variables must be declared before they can be used.
Challenge
Complete this chapter to unlock the next one.
Challenge
Task:
Create a HashMap<String, String> named 'codes'. Add ('US', 'United States'). Print the value for key 'US'.