Given an input string, print out the N most common characters in that string.
Anonymous
import java.util.*; public class freq { public static void frequency(String str, int N) { Map sortedFreqCount = new TreeMap(); for(int i = 0; i entry : sortedFreqCount.entrySet()) { if(printCount == N) break; Character key = entry.getKey(); Integer value = entry.getValue(); System.out.println(printCount + ".) " + key + " -> " + value); printCount++; } } public static > Map sortByValues(final Map map) { Comparator valueComparator = new Comparator() { public int compare(K k1, K k2) { int compare = map.get(k2).compareTo(map.get(k1)); if (compare == 0) return 1; else return compare; } }; Map sortedByValues = new TreeMap(valueComparator); sortedByValues.putAll(map); return sortedByValues; } public static void main(String[] args) { String test = "aaaaaaaaaaaaaaaaaaakkkkkkkkkkkkkkkkkkkddddddddddddhhhhhhhhhbbbbbbbeeeewqqqer"; frequency(test,10); } }
Check out your Company Bowl for anonymous work chats.