Count word frequencies in a paragraph (case-insensitive, ignoring punctuation) with a HashMap, then print the three most frequent words (ties broken alphabetically).
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());
}
}
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".