01 / 21

HashMap for
Counting & Grouping

Master Java's most versatile data structure for frequency counting, categorizing elements, and solving problems with key-value relationships.

Java Data Structures

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.

KEY "apple" "banana" "cherry" VALUE 3 5 2 Time Complexity
\( O(1) \) average
put, get, remove

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

Without HashMap
Nested loops scan the array for every element: \( O(n^2) \) comparisons.
With HashMap
One pass to count, one lookup per element: \( O(n) \) total time.

The Core HashMap API

put(key, value)
Insert or update a key-value pair. Overwrites if key exists.
get(key)
Returns the value for a key, or null if the key is absent.
getOrDefault(key, def)
Returns the value, or a default value if the key is missing.
containsKey(key)
Returns true if the map has the specified key.
remove(key)
Deletes the entry for this key. Returns the old value or null.
keySet()
Returns a Set of all keys for iteration.

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.

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

Java
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

INPUT ["a", "bb", "c", "bb", "a", "a"] COUNTING "a" 3 "bb" 2 "c" 1 Key → Integer GROUPING 1 ["a","c"] 2 ["bb","bb"] Key → List (grouped by string length)

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

1
Identify the key. What property are you counting or grouping by? (element value, length, first letter, etc.)
2
Choose the value type. Integer for counting, List for grouping.
3
Declare the HashMap with proper generics: HashMap<K, V>.
4
Iterate the data source and populate the map using getOrDefault (counting) or containsKey + put (grouping).
5
Query the map to answer the question: most frequent? all groups? specific count?

Example 1: Character Frequency

Problem: Given a String, count how many times each character appears.

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

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

Java
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

INPUT: [3, 1, 3, 2, 1, 3] STEP ELEMENT getOrDefault MAP STATE 1 3 0 + 1 = 1 {3=1} 2 1 0 + 1 = 1 {3=1, 1=1} 3 3 1 + 1 = 2 {3=2, 1=1} 4 2 0 + 1 = 1 {3=2, 1=1, 2=1} 5 1 1 + 1 = 2 {3=2, 1=2, 2=1} 6 3 2 + 1 = 3 {3=3, 1=2, 2=1} Result: {3=3, 1=2, 2=1}

Cleaner Grouping with computeIfAbsent

Java 8 introduced computeIfAbsent, which eliminates the manual "check then create" pattern for grouping.

Java
// 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

✕ NullPointerException
Calling .get(key) on a missing key returns null. Using the result without checking causes a crash. Use getOrDefault or containsKey first.
✕ Using == for String Keys
HashMap uses .equals() and .hashCode() internally. Comparing Strings with == checks reference, not content. Always use .equals().
✕ Forgetting Generics
Using raw types like HashMap map instead of HashMap<String, Integer> loses type safety and requires casting.

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?

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?