What I want to do is sort a map by value. I went over many questions that are available on the stackoverflow site and found out following solution that does what I want but missing a small thing.
Link1: Sorting Map
But the issue I am running into is that by default this is sorted by ascending order by value. I want to order it by descending order:
So what I did was I created a class that implements a comparator
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));
}
}
And then I pass my map to the treemap,
MyComparator comp = new MyComparator(myMap);
Map<String, Integer> newMap = new TreeMap(comp);
newMap.putAll(myMap);
This seems like bad approach because I feel this is inefficient. Is there a way to change the solution in the link to do ordering on descending order by default.
question from:
https://stackoverflow.com/questions/18923167/sorting-descending-order-java-map 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…