[!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.");
HashMap Patterns You Will Use Often
HashMap is one of the most useful Java collections because it turns a lookup problem into a key lookup. It is perfect for counting, caching, grouping, and quick existence checks with associated data.
Frequency Counting
String text = "banana";
Map<Character, Integer> frequency = new HashMap<>();
for (char ch : text.toCharArray()) {
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
}
Grouping Values
Map<String, List<String>> studentsByCity = new HashMap<>();
studentsByCity
.computeIfAbsent("Delhi", city -> new ArrayList<>())
.add("Asha");
getOrDefault and computeIfAbsent remove a lot of repetitive null-checking code.
Common Mistakes
- Calling
get()and assuming the result is nevernull. - Using mutable objects as keys and changing them after insertion.
- Forgetting that keys are unique and values can repeat.
- Expecting iteration order from plain
HashMap.
Mini Practice
Count how many times each word appears in a sentence. Store the result in a HashMap<String, Integer> and print each word with its count.
Practice Lab: Word Frequency Counter
Use HashMap to count repeated values efficiently.
- Create a sentence such as
"java is fun and java is powerful". - Split it into words.
- Use
HashMap<String, Integer>to count each word. - Use
getOrDefaultto simplify counting. - Print every word with its count.
Goal: Practice key-value thinking and frequency-map patterns.
Revision Checkpoint
HashMap: Stores key-value pairs.- Key uniqueness: One key maps to one current value.
put: Adds or replaces a value for a key.containsKey: Fast membership check for keys.- Pattern: Excellent for counting and lookup problems.
Before the quiz: Write the mental shape of a frequency map for words.