[!NOTE] Lists are great for storing sequential chains of items. But what if you need to rapidly search the collection? Searching a list of 1,000,000 users for a specific username takes a long time.
This is where dictionaries—or HashMaps in Java—become essential.
What is a HashMap?
A HashMap stores items in "key/value" pairs. You look up the "key", and it instantly spits out the "value" regardless of how large the dataset is.
If you want to store the capital cities of various countries:
- Key: The Country Name (String)
- Value: The Capital City Name (String)
Because it uses a highly complex mathematical hashing algorithm internally, a HashMap can retrieve an item out of 10,000,000 records in O(1) time (practically instantaneous), whereas an ArrayList might take O(N) time (checking each item in sequentially).
Syntax and Basics
To use it, import it from java.util.HashMap. Notice that when we establish the generics, we must provide TWO types: one for the Key, one for the Value.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// We create a HashMap that accepts a 'String' key, and maps it to a 'String' value
HashMap<String, String> capitalCities = new HashMap<String, String>();
// 1. ADDING DATA: We use .put() instead of .add()
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
// 2. RETRIEVING DATA: We pass the exact key
System.out.println(capitalCities.get("England")); // Outputs "London"
// 3. REMOVING DATA: Pass the exact key
capitalCities.remove("England");
// 4. CHECKING EXISTENCE: Lightning fast lookups!
if (capitalCities.containsKey("USA")) {
System.out.println("We have data for the USA!");
}
}
}
Modifying Existing Keys
A HashMap specifically uses a mathematical hash of the Key to locate the value in memory. Therefore, Keys must be absolutely unique!
If you use .put() with a key that already exists, it does not create a duplicate entry. Instead, it completely overwrites and destroys the old value with the new one.
capitalCities.put("USA", "Washington DC");
capitalCities.put("USA", "New York"); // OVERWRITES THE PREVIOUS LINE!
Advanced Types
You can mix and match types securely. Want to store the names of people mapping to their age?
// Key: String. Value: Integer wrapper.
HashMap<String, Integer> peopleAges = new HashMap<String, Integer>();
peopleAges.put("John", 32);
peopleAges.put("Steve", 45);
System.out.println("Steve is " + peopleAges.get("Steve") + " years old.");