Count the frequency of words with a HashMap

Description: Count the words of "the cat and the dog and the bird". Print each word with its count, in alphabetical order.

Hint:

  • Use a TreeMap (sorted keys) and merge(word, 1, Integer::sum).

Solution

import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        String text = "the cat and the dog and the bird";
        Map<String, Integer> counts = new TreeMap<>();

        for (String word : text.split(" ")) {
            counts.merge(word, 1, Integer::sum);
        }
        counts.forEach((word, n) -> System.out.println(word + " = " + n));
    }
}
Output

and = 2
bird = 1
cat = 1
dog = 1
the = 3

How it works

  • merge puts 1 if the word is new, or adds 1 to the old count.
  • A TreeMap keeps the keys sorted. A HashMap would print them in any order.

Read Java HashMap.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.