One of the most common HashMap patterns is the frequency counter. You scan through a collection and count how many times each element appears:
String[] words = {"apple", "banana", "apple", "cherry", "banana", "apple"};
HashMap<String, Integer> freq = new HashMap<>();
for (String w : words) {
freq.put(w, freq.getOrDefault(w, 0) + 1);
}
After the loop, freq holds {"apple": 3, "banana": 2, "cherry": 1}. The trick is .getOrDefault(w, 0). If the word has not been seen yet, it starts at , and you add . If it already exists, you get the current count and add .
This pattern appears everywhere: counting characters in a string, tallying votes, building histograms. Memorize it.