我之前需要按其值对 HashMap 进行排序,并且我将比较器与集合一起使用,如下所示:
private LinkedHashMap<String, Integer> sortMap(Map<String, Integer> results, int count)
{
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(results.entrySet());
Comparator<Entry<String, Integer>> comparator = new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {
return b.getValue().compareTo(a.getValue());
}
};
Collections.sort(entries, comparator);
LinkedHashMap<String, Integer> sorted = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : entries)
sorted.put(entry.getKey(), entry.getValue());
return sorted;
}
现在情况发生了变化,我需要它是一个经过排序的 HashMap。所以我将代码更改为如下所示:
private LinkedHashMap<String, Double> sortMap(Map<String, Double> results, int count)
{
List<Map.Entry<String, Double>> entries = new ArrayList<Map.Entry<String, Double>>(results.entrySet());
Comparator<Entry<String, Double>> comparator = new Comparator<Entry<String, Double>>() {
@Override
public int compare(Entry<String, Double> a, Entry<String, Double> b) {
return b.getValue().compareTo(a.getValue());
}
};
Collections.sort(entries, comparator);
LinkedHashMap<String, Double> sorted = new LinkedHashMap<String, Double>();
for (Entry<String, Double> entry : entries)
sorted.put(entry.getKey(), entry.getValue());
return sorted;
}
它抛出一个错误,即java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
在:
at myPackage.myClass$1.compare(myClass.java:124)
at myPackage.myClass$1.compare(myClass.java:1)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at myPackage.myClass.sortMap(myClass.java:128)
myClass.java.128 :Collections.sort(entries, comparator);
myClass.java.124 :return b.getValue().compareTo(a.getValue());
你们的任何帮助将不胜感激,谢谢!