我需要找到topN键.
我有一个输入作为HashMap的形式为(键:值):
Banana : 13
Apple: 12
Mango : 32
Orange : 12
Grape : 18
Pear : 12
Peach : 18
Run Code Online (Sandbox Code Playgroud)
我创建了一个链接的HapMap,它根据值排序:
private static <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map) {
List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
Map<K, V> sortedMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
} …Run Code Online (Sandbox Code Playgroud)