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".
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!