I want to write a comparator that will let me sort a TreeMap by value instead of the default natural ordering.
I tried something like this, but can\'t find out what
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeMap initTree = new TreeMap();
initTree.put("D", 0);
initTree.put("C", -3);
initTree.put("A", 43);
initTree.put("B", 32);
System.out.println("Sorted by keys:");
System.out.println(initTree);
List list = new ArrayList(initTree.entrySet());
Collections.sort(list, new Comparator>() {
@Override
public int compare(Map.Entry e1, Map.Entry e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
System.out.println("Sorted by values:");
System.out.println(list);
}
}