HashMap for
Counting & Grouping
Master Java's most versatile data structure for frequency counting, categorizing elements, and solving problems with key-value relationships.
What is a HashMap?
A HashMap stores data as key-value pairs. Each key maps to exactly one value. You can look up, insert, or remove any entry in average \( O(1) \) time: essentially instant.
Why Use HashMap for Counting?
Many programming problems require you to count how often each element appears. Without a HashMap, you'd need nested loops running in \( O(n^2) \) time. A HashMap reduces this to \( O(n) \).
The Core HashMap API
The Counting Pattern
The frequency counting pattern is the single most common HashMap usage. For every element, read the current count (defaulting to 0 if absent) and increment by 1.
HashMap<String, Integer> freq = new HashMap<>(); for (String item : array) { freq.put(item, freq.getOrDefault(item, 0) + 1); }
The Grouping Pattern
Instead of counting, sometimes you need to group elements by a shared property. The value becomes a List of items that share the same key.
HashMap<Integer, List<String>> groups = new HashMap<>(); for (String word : words) { int len = word.length(); if (!groups.containsKey(len)) { groups.put(len, new ArrayList<>()); } groups.get(len).add(word); }
Counting vs Grouping
HashMap vs TreeMap
| HashMap | TreeMap | |
|---|---|---|
| Ordering | No guaranteed order | Sorted by key |
| put / get | \( O(1) \) average | \( O(\log n) \) |
| Null keys | Allows one null key | Does not allow null |
| Use when | Speed is priority | Sorted iteration needed |
| Underlying structure | Hash table (array + buckets) | Red-black tree |
How to Apply the Pattern
Example 1: Character Frequency
Problem: Given a String, count how many times each character appears.
public static HashMap<Character, Integer> charFreq(String s) { HashMap<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } return map; }
Example 2: Most Frequent Element
Problem: Given an int array, find the element that appears the most.
public static int mostFrequent(int[] arr) { if (arr == null || arr.length == 0) { throw new IllegalArgumentException("Array is empty"); } HashMap<Integer, Integer> freq = new HashMap<>(); for (int n : arr) { freq.put(n, freq.getOrDefault(n, 0) + 1); } int maxKey = arr[0], maxCount = 0; for (int key : freq.keySet()) { if (freq.get(key) > maxCount) { maxCount = freq.get(key); maxKey = key; } } return maxKey; }
Example 3: Group Anagrams
Problem: Given a list of words, group words that are anagrams of each other.
public static List<List<String>> groupAnagrams(String[] words) { HashMap<String, List<String>> map = new HashMap<>(); for (String w : words) { char[] chars = w.toCharArray(); Arrays.sort(chars); String key = new String(chars); if (!map.containsKey(key)) map.put(key, new ArrayList<>()); map.get(key).add(w); } return new ArrayList<>(map.values()); }
Tracing the Counting Pattern
Cleaner Grouping with computeIfAbsent
Java 8 introduced computeIfAbsent, which eliminates the manual "check then create" pattern for grouping.
// Before: manual check if (!map.containsKey(key)) map.put(key, new ArrayList<>()); map.get(key).add(value); // After: one line with computeIfAbsent map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
Common Mistakes
Summary: Patterns at a Glance
| Counting | Grouping | |
|---|---|---|
| Value type | Integer | List<T> |
| Core method | getOrDefault(key, 0) | computeIfAbsent(key, k->new List) |
| Update step | put(key, count + 1) | get(key).add(item) |
| Example use | Character frequency | Group anagrams |
| Time complexity | \( O(n) \) | \( O(n) \) (plus key generation time) |
Question 1 of 5
What does map.getOrDefault("x", 0) return if the key "x" is not in the map?
Question 2 of 5
Which line correctly increments the count for a key in a HashMap<String, Integer>?
Question 3 of 5
After running this code, what does map contain?
HashMap<String, Integer> map = new HashMap<>();
String[] arr = {"a", "b", "a", "c", "b", "a"};
for (String s : arr) {
map.put(s, map.getOrDefault(s, 0) + 1);
}
Question 4 of 5
When grouping elements into lists, what must you do before calling map.get(key).add(value)?
Question 5 of 5
What is the average time complexity of inserting \( n \) elements into a HashMap using the counting pattern?