HashMap for
Storage & Counting
Master Java's most powerful data structure for key-value storage and frequency counting patterns used in real-world applications and coding interviews.
What Is a HashMap?
A HashMap is a data structure that stores data as key-value pairs. Think of it like a dictionary: you look up a word (the key) and instantly find its definition (the value).
How Hashing Works
Why Use a HashMap?
Core API Methods
More Essential Methods
HashMap vs Other Collections
| HashMap | TreeMap | ArrayList | |
|---|---|---|---|
| Access by | Key | Key | Index |
| Lookup Time | \( O(1) \) | \( O(\log n) \) | \( O(1) \) |
| Ordered? | No | Yes (sorted) | Yes (insertion) |
| Duplicates? | Keys: No | Keys: No | Yes |
| Best For | Fast lookup | Sorted keys | Sequential data (\( O(n) \) search) |
How to Use HashMap: Step by Step
Example 1: Student Grades
Store student names as keys and their grades as values, then look up a specific student.
Example 2: Frequency Counting
Count how many times each word appears in an array. This is the most common HashMap pattern.
Counting Step by Step
Example 3: Find the Most Frequent Element
After counting frequencies, iterate to find the key with the highest value.
Example 4: Two Sum Problem
Given an array and a target sum, find two indices whose values add up to the target. HashMap makes this \( O(n) \) instead of \( O(n^2) \).
Common Mistakes
Method Quick Reference
| Method | Returns | Description |
|---|---|---|
| put(K, V) | Previous V or null | Insert or overwrite entry |
| get(K) | V or null | Retrieve value for key |
| getOrDefault(K, def) | V or def | Safe retrieval with fallback |
| containsKey(K) | boolean | Check if key exists |
| remove(K) | V or null | Delete entry by key |
| size() | int | Number of entries |
| keySet() | Set<K> | All keys |
| entrySet() | Set<Entry> | All key-value pairs |
Question 1 of 5
What is the average time complexity of the get() method in a HashMap?
Question 2 of 5
What does the following code print?
HashMap<String, Integer> m = new HashMap<>();
m.put("x", 10);
m.put("y", 20);
m.put("x", 30);
System.out.println(m.get("x"));
Question 3 of 5
Which line correctly counts the frequency of each character in a String?
Question 4 of 5
Which of the following is a valid HashMap declaration in Java?
Question 5 of 5
In the Two Sum problem, what does the HashMap store?