Collections · 348 words · 2 minute read
Java HashMap Patterns: Counts, Complements, and Grouping
By Priyanshu Rauth · Published 2026-09-04 · Updated 2026-09-04
A HashMap is most useful when a later decision depends on something you saw earlier. It can count occurrences, remember a first index, map a word to a group, or test whether a complement already exists. The common shape is simple: decide what the key represents, decide what the value represents, then update and query in an order that respects the problem’s rules.
Frequency counts
For a count, the key is an item and the value is its observed total. getOrDefault(key, 0) + 1 makes the initialization rule explicit. Normalize strings before using them as keys if the contract ignores case or punctuation. Do not normalize blindly: user-visible spelling and the grouping key may need to be stored separately.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
int[] values = {2, 7, 11, 15};
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < values.length; i++) {
Integer other = seen.get(9 - values[i]);
if (other != null) { System.out.println(other + ", " + i); return; }
seen.put(values[i], i);
}
}
}The output is 0, 1. Looking up before inserting means one position cannot pair with itself. It also makes duplicate inputs such as 3, 3 work naturally on the second occurrence.
Grouping and ordering
Grouping uses a map from a canonical key to a collection. For anagrams, a sorted-letter signature can be the key and a list of original words the value. Use computeIfAbsent to create that list only on the first occurrence. If rendered group order matters, choose LinkedHashMap or sort intentionally rather than relying on HashMap’s implementation details.
Common mistakes
- Using a mutable object as a key and changing it after insertion.
- Confusing an absent key with a key deliberately mapped to null.
- Accidentally overwriting an earlier index before it is needed.
- Leaking HashMap’s unspecified order into tests or UI output.
Practice next
Solve two sum with HashMap, first unique element, and group anagrams. For a DSA version of the complement pattern, visit unsorted two sum. Each problem uses a map, but the key and value mean something different.
Continue with the Java practice path · Try code in the Java compiler