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
Java ArrayList
Java HashMap
Java HashSet and LinkedList
Java Generics
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?