Word Frequency Counter in Java: Explanation & Practice
Count word frequencies in a file
Problem summary
Read a text file and count the frequency of each word, then print top 5.
Starter code
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
// Read file, count word frequencies
// Print top 5 words with counts
// Format: word: count
}
}Expected output and test cases
- Top 5 words
the: 10 a: 8 is: 6 to: 5 and: 4
- Simple file
hello: 3 world: 2 java: 1
- Empty file
empty file
Hints
- Split lines into words
- Use HashMap for counting
- Sort by value descending
Related File I/O exercises
- Practice Find and Replace in File in Java
- Practice Log File Parser in Java
- Practice Simple File Encryption in Java
Practice all File I/O exercises · Run this idea in the Java compiler