LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · HashMap and TreeMap Programs · Question 1

Word frequency with the top three words in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Count word frequencies in a paragraph (case-insensitive, ignoring punctuation) with a HashMap, then print the three most frequent words (ties broken alphabetically).

Solution
Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String text = "Java is fun. Java is fast, and Java is everywhere! Learning Java is fun and useful.";
        Map<String, Integer> freq = new HashMap<>();
        for (String w : text.toLowerCase().split("[^a-z]+")) {
            if (!w.isEmpty()) freq.merge(w, 1, Integer::sum);
        }
        List<Map.Entry<String, Integer>> entries = new ArrayList<>(freq.entrySet());
        entries.sort(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()));
        System.out.println(freq.size() + " distinct words");
        for (Map.Entry<String, Integer> e : entries.subList(0, 3)) System.out.println(e.getKey() + " " + e.getValue());
    }
}

Output Verified by compiling and running

8 distinct words
is 4
java 4
and 2

merge counts; the entries are then sorted by count (descending) and word. "and" and "fun" both have 2 – alphabetical order picks "and".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links