Count the words that matter
A support tool skims ticket text to see which terms keep coming up, ignoring the little joining words.
- Split on whitespace and compare in lowercase.
- Words shorter than three characters are noise and are left out.
- The result maps each remaining word to how many times it appeared.
wordFrequency(text: string) → map<string, int>
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
Map<String, Integer> wordFrequency(String text) {
}
Worked examples
| Call | Result |
|---|---|
wordFrequency("card declined card") | Main.<String, Integer>mp("card", 2, "declined", 1) |
wordFrequency("The the THE") | Main.<String, Integer>mp("the", 3) |
wordFrequency("a an I ok") | Main.<String, Integer>mp() |
wordFrequency("") | Main.<String, Integer>mp() |
Hint
Lowercase before counting, or "Payment" and "payment" end up as two entries.
Reference solution in Java
Map<String, Integer> wordFrequency(String text) {
Map<String, Integer> result = new LinkedHashMap<>();
for (String w : text.toLowerCase().trim().split("\\s+")) {
if (w.length() < 3) continue;
result.merge(w, 1, Integer::sum);
}
return result;
}