Word Frequency Counter in Java: Explanation & Practice

Count word frequencies in a sentence

Problem summary

Write a program that counts how many times each word appears in a sentence.

Starter code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String sentence = "the quick brown fox jumps over the lazy dog the"; // Test case 1
        
        // Count word frequencies
        // Print each word and count (alphabetical order)
    }
}

Expected output and test cases

  • Word frequencies
    brown: 1
    dog: 1
    fox: 1
    jumps: 1
    lazy: 1
    over: 1
    quick: 1
    the: 3
  • Simple frequencies
    a: 3
    b: 2
    c: 1
  • Same word repeated
    hello: 5

Hints

  1. Use HashMap<String, Integer>
  2. getOrDefault() for counting
  3. Sort keys for output

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler