01 / 20

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.

Java

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).

Key
A unique identifier used to store and retrieve data. Keys cannot be duplicated.
Value
The data associated with a key. Values can be duplicated across different keys.

How Hashing Works

"apple" "banana" "cherry" hashCode() % capacity Buckets [0] empty [1] empty [2] apple:5 [3] banana:3 [4] empty [5] cherry:7

Why Use a HashMap?

★ Fast Lookups
Retrieve any value in \( O(1) \) average time, no matter how many entries exist.
★ Counting
Count occurrences of elements with a simple pattern: increment the value for each key.
★ Flexible Types
Keys and values can be any object type: String, Integer, custom classes, and more.

Core API Methods

// Declaration HashMap<String, Integer> map = new HashMap<>(); // Insert or update a key-value pair map.put("apple", 5); // Retrieve the value for a key int count = map.get("apple"); // returns 5 // Check if a key exists boolean has = map.containsKey("apple"); // true // Get with a default if key is absent int val = map.getOrDefault("grape", 0); // returns 0 // Remove a key-value pair map.remove("apple");

More Essential Methods

// Get number of entries int size = map.size(); // Check if empty boolean empty = map.isEmpty(); // Get all keys Set<String> keys = map.keySet(); // Get all values Collection<Integer> vals = map.values(); // Iterate over all entries for (Map.Entry<String, Integer> e : map.entrySet()) { System.out.println(e.getKey() + " : " + e.getValue()); }

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

1
Identify the key and value types. What will you look up by? What data do you need to store?
2
Declare the HashMap. Use the diamond operator: HashMap<K, V> map = new HashMap<>();
3
Populate with put(). Add entries one by one or inside a loop over your data.
4
Retrieve with get() or getOrDefault(). Always use getOrDefault when the key might not exist.
5
Iterate with entrySet(). Process all entries when you need to read the full map.

Example 1: Student Grades

Store student names as keys and their grades as values, then look up a specific student.

HashMap<String, Integer> grades = new HashMap<>(); grades.put("Alice", 95); grades.put("Bob", 87); grades.put("Carol", 92); System.out.println(grades.get("Bob")); // Output: 87 // Update Bob's grade grades.put("Bob", 91); System.out.println(grades.get("Bob")); // Output: 91

Example 2: Frequency Counting

Count how many times each word appears in an array. This is the most common HashMap pattern.

String[] words = {"cat", "dog", "cat", "bird", "dog", "cat"}; HashMap<String, Integer> freq = new HashMap<>(); for (String w : words) { freq.put(w, freq.getOrDefault(w, 0) + 1); } // freq = {cat=3, dog=2, bird=1}

Counting Step by Step

Input Array "cat" "dog" "cat" "bird" "dog" "cat" Step Word Action Map State 1 "cat" put("cat", 0+1) {cat=1} 2 "dog" put("dog", 0+1) {cat=1, dog=1} 3 "cat" put("cat", 1+1) {cat=2, dog=1} 4 "bird" put("bird", 0+1) {cat=2, dog=1, bird=1} 5 "dog" put("dog", 1+1) {cat=2, dog=2, bird=1} 6 "cat" put("cat", 2+1) {cat=3, dog=2, bird=1} Final Result: cat=3, dog=2, bird=1

Example 3: Find the Most Frequent Element

After counting frequencies, iterate to find the key with the highest value.

// After building freq map from previous example String maxKey = ""; int maxCount = 0; for (Map.Entry<String, Integer> entry : freq.entrySet()) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); maxKey = entry.getKey(); } } System.out.println(maxKey + " appears " + maxCount + " times"); // Output: cat appears 3 times

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) \).

public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> seen = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (seen.containsKey(complement)) { return new int[]{seen.get(complement), i}; } seen.put(nums[i], i); } return new int[]{}; }

Common Mistakes

✕ Using get() on Missing Key
Calling get(key) when the key doesn't exist returns null, which causes NullPointerException when unboxing to int. Always use getOrDefault() or check with containsKey() first.
✕ Primitive Types as Generics
Writing HashMap<int, int> won't compile. HashMap requires wrapper classes: use Integer, String, Double, not int, char, double.
✕ Assuming Order
HashMap does not maintain insertion order. If order matters, use LinkedHashMap for insertion order or TreeMap for sorted keys.
✕ Forgetting Import
You must add import java.util.HashMap; at the top of your file. Missing this causes a compilation error that's easy to overlook.

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?

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?