[英]Using tree map for sorting in descending order by values
I just have a map implementation below to sort the values in descending order and I have used the below implementation. 我下面只有一个map实现,可以按降序对值进行排序,并且我使用了下面的实现。
public static Map<String,Integer> sortByComparator(Map<String,Integer> unsortMap) {
List list = new LinkedList(unsortMap.entrySet());
//sort list based on comparator
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
});
//put sorted list into map again
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
This does the necessary functions.. But I am curious to know whether I will be able to use tree map to sort this by descending order 这会执行必要的功能。但是我很好奇我是否能够使用树形图按降序对它进行排序
您不会,因为TreeMap是按键顺序排序的,而您是按值排序的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.