How can I sort a treemap using its values rather than the key?
You could try giving a Comparator that compare values instead of keys when you create the TreeMap.
final TreeMap tree = new TreeMap();
tree.put(1, "1");
tree.put(2, "2");
tree.put(3, "3");
tree.put(4, "4");
final TreeMap treeSortedByValues = new TreeMap(new Comparator()
{
public int compare(Integer o1, Integer o2)
{
return tree.get(o1).compareTo(tree.get(o2));
}
});
treeSortedByValues.putAll(tree);
for ( Entry e : treeSortedByValues.entrySet() )
{
System.out.println(e.getKey() + ": " + e.getValue());
}