Word Frequency Counter in Java: Solution, Explanation & Practice
Count word frequencies in a sentence
Problem summary
Write a program that counts how many times each word appears in a sentence.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
String sentence = "the quick brown fox jumps over the lazy dog the"; // Test case 1
// Count word frequencies
// Print each word and count (alphabetical order)
}
}Expected output and test cases
- Word frequencies
brown: 1 dog: 1 fox: 1 jumps: 1 lazy: 1 over: 1 quick: 1 the: 3
- Simple frequencies
a: 3 b: 2 c: 1
- Same word repeated
hello: 5
Hints
- Use HashMap<String, Integer>
- getOrDefault() for counting
- Sort keys for output
Validated solution
Reveal Java solution
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String[] words = "the quick brown fox jumps over the lazy dog the".split(" ");
Map<String, Integer> counts = new TreeMap<>();
for (String word : words) counts.put(word, counts.getOrDefault(word, 0) + 1);
for (Map.Entry<String, Integer> entry : counts.entrySet()) System.out.println(entry.getKey() + ": " + entry.getValue());
}
}How to approach the problem
A map connects each word to its count. TreeMap keeps keys in alphabetical order, which makes the shown output stable; HashMap would be fine if ordering did not matter.
Approach
- Split or tokenize the sentence according to the exercise’s word rule.
- Increment getOrDefault for each word.
- Choose an ordered map only when ordered output is required.
Time and space complexity
Time: O(n log k) with TreeMap. Space: O(k).
Edge cases to test
- Case normalization changes whether The and the are one key.
- Punctuation may need removal before counting.
Common mistakes
- Using a list and repeatedly scanning it for every word.
- Assuming HashMap iteration is alphabetical.
Follow-up challenge
Count words from a streaming reader without retaining the full text.
Related Collections exercises
- Practice Queue Operations in Java
- Practice Stack Operations in Java
- Practice Remove Duplicates from List in Java
Practice all Collections exercises · Run this idea in the Java compiler