由于您可能有重复的值,因此您不应该使用Set
根本不。更改为List
并对其进行排序。你的entriesSortedByValues
看起来像这样:
static <K,V extends Comparable<? super V>>
List<Entry<K, V>> entriesSortedByValues(Map<K,V> map) {
List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet());
Collections.sort(sortedEntries,
new Comparator<Entry<K,V>>() {
@Override
public int compare(Entry<K,V> e1, Entry<K,V> e2) {
return e2.getValue().compareTo(e1.getValue());
}
}
);
return sortedEntries;
}
注意:在您的示例输出中,值是递减的。如果您希望它们上升,请使用e1.getValue().compareTo(e2.getValue())
反而。
Example:
public static void main(String args[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 34);
map.put("B", 25);
map.put("C", 50);
map.put("D", 50); // "duplicate" value
System.out.println(entriesSortedByValues(map));
}
Output:
[D=50, C=50, A=34, B=25]