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
You could simply invert the return value of your compare method by adding a minus sign at the beginning:
return -((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
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();
now u can iterate over iterator and extract the value using iterator.hasNext() and iterator.next() methods ......
This will work :
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;
}
});
You should use new TreeMap<>(Collections.reverseOrder());
.
Map<String, Integer> newMap = new TreeMap<>(Collections.reverseOrder());
newMap.putAll(myMap);
or to reverse an existing comparator like the value-comparator Collections.reverseOrder(comparator)
. It works like your approach swapping the two objects before invoking compare
/compareTo
.
To change the solution in the link to sort by descending order, just reverse the condition:
...
// 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
}
...