Word Frequency Program in Java
Problem
A HashMap stores key-value pairs, making it a natural fit for counting how often each item in a collection appears.
Given a sentence, count how many times each word appears.
Java Program
import java.util.HashMap;
import java.util.Map;
public class WordFrequency {
public static void main(String[] args) {
String text = "the quick fox the lazy fox the dog";
Map<String, Integer> freq = new HashMap<>();
for (String word : text.split(" ")) {
// getOrDefault(word, 0) reads the current count, or 0 if unseen, then increments it
freq.put(word, freq.getOrDefault(word, 0) + 1);
}
for (Map.Entry<String, Integer> entry : freq.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}Output
Core Logic
A HashMap makes this straightforward — split the sentence into words and bump each word's count as you go.
- 1
text.split(" ")breaks the sentence into individual words. - 2A
HashMap<String, Integer>tracks each word's running count. - 3
freq.getOrDefault(word, 0)reads the current count, or0if the word hasn't been seen yet. - 4Adding
1and callingfreq.put(word, ...)stores the updated count in one line. - 5
entrySet()is iterated afterward to print every word alongside its final count.
"the quick fox the lazy fox the dog", "the" ends with a count of 3 and "fox" ends with a count of 2.Key Point: getOrDefault() removes the need for a separate 'does this key exist yet' check before incrementing.
Why: Every word is visited once to update its count, and the map holds one entry per distinct word, up to n in the worst case.
Key Concepts
Approach 2: Streams + Collectors.groupingBy()
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class WordFrequencyStream {
public static void main(String[] args) {
String text = "the quick fox the lazy fox the dog";
// Groups equal words together and counts how many are in each group
Map<String, Long> freq = Arrays.stream(text.split(" "))
.collect(Collectors.groupingBy(word -> word, Collectors.counting()));
freq.forEach((word, count) -> System.out.println(word + ": " + count));
}
}
Output
Core Logic
Streams can express the same idea more declaratively — groupingBy plus counting() builds the frequency map in one line.
- 1
Arrays.stream(text.split(" "))turns the split words into aStream<String>. - 2
Collectors.groupingBy(word -> word, Collectors.counting())groups equal words together and counts how many are in each group. - 3The result is a
Map<String, Long>— note the count is aLong, not anint, sincecounting()always produces one. - 4
freq.forEach((word, count) -> ...)prints every entry using a lambda instead of an explicitentrySet()loop.
"the quick fox the lazy fox the dog" produces the same counts as the manual version: the: 3, quick: 1, lazy: 1, dog: 1, fox: 2.Key Point: groupingBy + counting() is the idiomatic modern-Java way to build a frequency map — it reads as 'group by identity, then count', with no manual increment logic at all.
Why: groupingBy() still visits every word once while building the map, which holds one entry per distinct word just like the manual version.
Key Concepts
Interview Questions
How do you ignore punctuation when counting words?
Lower-case the text and split on non-word characters, for example text.toLowerCase().split("\\W+").
How do you find the three most common words?
Sort the map's entries by value in descending order and take the first three, for example with stream().sorted(...).limit(3).