Character Frequency Counter with a HashMap
javaJavabeginnerinterview-prepjava
Count how often each character appears with Map of Character to Integer and merge, then print the most frequent first.
import java.util.*;
public class CharacterFrequency {
public static void main(String[] args) {
Map<Character, Integer> counts = countCharacters("hello world");
List<Map.Entry<Character, Integer>> entries = new ArrayList<>(counts.entrySet());
entries.sort(Map.Entry.<Character, Integer>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()));
for (Map.Entry<Character, Integer> entry : entries) {
System.out.println("'" + entry.getKey() + "': " + entry.getValue());
}
}
// O(n) time. merge() inserts 1 for a new character, or adds 1 to the existing count.
static Map<Character, Integer> countCharacters(String text) {
Map<Character, Integer> counts = new HashMap<>();
for (char c : text.toCharArray()) {
if (c == ' ') continue;
counts.merge(c, 1, Integer::sum);
}
return counts;
}
}