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

  1. Split lines into words
  2. Use HashMap for counting
  3. Sort by value descending

Related File I/O exercises

Practice all File I/O exercises · Run this idea in the Java compiler