How can I sort a treemap using its values rather than the key?
Try this. This sorts TreeMap values in ascending order, assuming that is how you want the values to be sorted.
static Map sortByValues(Map map) {
List> list = new ArrayList(map.entrySet());
// copy Map to List to use Comparator
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) o1).getValue()).compareTo(((Map.Entry) o2).getValue());
}
});
// then copy List to LinkedHashMap as it preserves insertion order
Map result = new LinkedHashMap();
Iterator itr = list.iterator();
while (itr.hasNext()) {
Map.Entry m = (Map.Entry) itr.next();
result.put(m.getKey(), m.getValue());
}
return result;
}