Step 2: Counting the Words Using a HashMap
Why a HashMap?
A HashMap provides an efficient way to store key-value pairs. In our case, the word will be the key, and its frequency will be the value. This will enable us to look up the frequency of a word in constant time.
How to Count?
We'll initialize an empty HashMap (or an object in JavaScript, or a dictionary in Python) to store the occurrences of each word. Let's call this HashMap occurrences
.
Code Snippet for Counting
Here's how you can populate the occurrences
HashMap:
1Map<String, Integer> occurrences = new HashMap<>();
2for(String word : split_s) {
3 if(occurrences.containsKey(word)) {
4 occurrences.put(word, occurrences.get(word) + 1);
5 } else {
6 occurrences.put(word, 1);
7 }
8}