[英]Sorting Descending order: Java Map
我想要做的是按值排序地圖。 我找了很多關於stackoverflow網站上可用的問題,並找到了以下解決方案,它做了我想要的但卻錯過了一件小事。
Link1 :排序地圖
但我遇到的問題是默認情況下按值按升序排序。 我想按降序排序:
所以我做的是創建了一個實現比較器的類
class MyComparator implements Comparator {
Map map;
public MyComparator(Map map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
return ((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
}
}
然后我將我的地圖傳遞給樹圖,
MyComparator comp = new MyComparator(myMap);
Map<String, Integer> newMap = new TreeMap(comp);
newMap.putAll(myMap);
這似乎是不好的方法,因為我覺得這是低效的。 有沒有辦法在鏈接中更改解決方案,默認情況下按降序排序。
你應該使用new TreeMap<>(Collections.reverseOrder());
。
Map<String, Integer> newMap = new TreeMap<>(Collections.reverseOrder());
newMap.putAll(myMap);
或者反轉現有的比較器,如值比較器Collections.reverseOrder(comparator)
。 它的工作方式類似於在調用compare
/ compareTo
之前交換兩個對象的方法。
TreeMap<Long,String> treeMap = new TreeMap<Long,String>();
NavigableMap <Long, String> nmap = treeMap.descendingMap();
Set<Long, String> set = nmap.entrySet();
Iterator<Long, String> iterator = set.iterator();
現在你可以迭代迭代器並使用iterator.hasNext()和iterator.next()方法提取值......
這將有效:
TreeMap<Integer, Integer> reverseInteger=new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2>o1?1:o2==o1?0:-1;
}
});
您可以通過在開頭添加減號來簡單地反轉比較方法的返回值:
return -((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
要更改鏈接中的解決方案以按降序排序,只需反轉條件:
...
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return 1; // For ascending, return -1;
} else {
return -1; // For ascending, return 1;
} // returning 0 would merge keys
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.