Java 8: Count word frequencies in a text. How many ways can you solve it, from feasible to optimal?
Problem
Given a paragraph, return how many times each word occurs (case-insensitive, ignoring punctuation). Interviewers use it to see whether you know the classic HashMap pattern, the Java 8 Map additions (merge, getOrDefault, compute) and the Streams Collectors, and whether you can reason about cost.
Approach 1: Brute force (feasible, O(n²))
For each distinct word, scan the whole array again and count. Easy to write, but every word triggers a full pass.
import java.util.LinkedHashMap;
import java.util.Map;
class WordCountBrute {
static Map<String, Integer> count(String text) {
String[] words = text.toLowerCase().split("\\W+");
Map<String, Integer> result = new LinkedHashMap<>();
for (String w : words) {
if (w.isEmpty() || result.containsKey(w)) continue;
int c = 0;
for (String other : words) if (other.equals(w)) c++; // full scan per distinct word
result.put(w, c);
}
return result;
}
}Time O(n × d) where d is the number of distinct words, O(n²) in the worst case.
Approach 2: HashMap, Java 7 style (O(n))
One pass; read the current count and write it back. Correct and linear, but it performs two hash lookups per word and needs a null check.
import java.util.HashMap;
import java.util.Map;
class WordCountJava7 {
static Map<String, Integer> count(String text) {
Map<String, Integer> counts = new HashMap<>();
for (String w : text.toLowerCase().split("\\W+")) {
if (w.isEmpty()) continue;
Integer c = counts.get(w); // lookup 1
counts.put(w, c == null ? 1 : c + 1); // lookup 2
}
return counts;
}
}Approach 3: Java 8 Map.merge (O(n), the idiomatic loop)
merge(key, 1, Integer::sum) inserts 1 if absent or combines with the existing value, in a single call. getOrDefault and compute are equivalent alternatives.
import java.util.HashMap;
import java.util.Map;
class WordCountMerge {
static Map<String, Integer> count(String text) {
Map<String, Integer> counts = new HashMap<>();
for (String w : text.toLowerCase().split("\\W+")) {
if (!w.isEmpty()) counts.merge(w, 1, Integer::sum);
// alternatives: counts.put(w, counts.getOrDefault(w, 0) + 1);
// counts.compute(w, (k, v) -> v == null ? 1 : v + 1);
}
return counts;
}
}Approach 4: Java 8 Streams with groupingBy (O(n), declarative)
groupingBy(identity, mapFactory, counting()) expresses the whole intent in one pipeline. Passing TreeMap::new gives alphabetical keys; LinkedHashMap::new keeps first-seen order. Counts are Long.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
class WordCountStreams {
private static final Pattern NON_WORD = Pattern.compile("\\W+");
static Map<String, Long> count(String text) {
return NON_WORD.splitAsStream(text.toLowerCase())
.filter(w -> !w.isEmpty())
.collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()));
}
// Typical follow-up: the top N words, most frequent first, ties alphabetical
static List<Map.Entry<String, Long>> topN(String text, int n) {
return count(text).entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()))
.limit(n)
.collect(Collectors.toList());
}
}Approach 5: Parallel streams for very large input (O(n / cores))
For gigabytes of text split into lines, groupingByConcurrent lets all cores update one ConcurrentHashMap without a merge step. Only worth it for large, CPU-bound inputs.
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
class WordCountParallel {
static ConcurrentMap<String, Long> count(List<String> lines) {
return lines.parallelStream()
.flatMap(line -> Arrays.stream(line.toLowerCase().split("\\W+")))
.filter(w -> !w.isEmpty())
.collect(Collectors.groupingByConcurrent(Function.identity(), Collectors.counting()));
}
}Run all approaches
import java.util.Arrays;
import java.util.TreeMap;
class WordCountDemo {
public static void main(String[] args) {
String text = "The quick brown fox jumps over the lazy dog. The dog sleeps!";
System.out.println(WordCountBrute.count(text));
System.out.println(new TreeMap<>(WordCountJava7.count(text)));
System.out.println(new TreeMap<>(WordCountMerge.count(text)));
System.out.println(WordCountStreams.count(text));
System.out.println(WordCountStreams.topN(text, 2)); // [the=3, dog=2]
System.out.println(new TreeMap<>(WordCountParallel.count(Arrays.asList(text.split("\\.")))));
}
}Feasible → optimal
- Brute force: O(n²); acceptable only for tiny inputs.
- HashMap get/put: O(n), two lookups per word.
Map.merge: O(n), one call per word; the best plain loop.- Streams
groupingBy: O(n), most readable; small overhead for boxingLongand stream setup. - Parallel
groupingByConcurrent: O(n / cores) for very large inputs; slower than 3 or 4 for small ones.
What to say in the interview
Start with the HashMap idea, write it with merge (or groupingBy if they ask for streams), state O(n) time and O(d) space, then mention parallelism only for huge inputs and that splitting with a precompiled Pattern avoids recompiling the regex.
Follow-up questions interviewers ask
Try answering each one before you open it.
Why is the merge version faster than get-then-put?
merge finds the bucket once and updates the node in place, while get + put hashes the key and walks the bucket twice and allocates a new Integer through put. The difference is small per call but measurable in hot loops. It also removes the null check, which makes the code less error-prone.
How would you count words in a 50 GB file that does not fit in memory?
Stream it with Files.lines(path) (lazy, line by line) so the text never has to fit in memory; only the map of distinct words does. If the vocabulary itself is too large, partition: hash each word into one of N temporary files, count each file separately, and merge, which is the MapReduce pattern. For approximate top-K, a Count-Min Sketch plus a small heap uses constant memory.