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
A lot of people hear adviced to use List and i prefer to use it as well
here are two methods you need to sort the entries of the Map according to their values.
static final Comparator> DOUBLE_VALUE_COMPARATOR =
new Comparator>() {
@Override
public int compare(Entry, Double> o1, Entry, Double> o2) {
return o1.getValue().compareTo(o2.getValue());
}
};
static final List> sortHashMapByDoubleValue(HashMap temp)
{
Set> entryOfMap = temp.entrySet();
List> entries = new ArrayList>(entryOfMap);
Collections.sort(entries, DOUBLE_VALUE_COMPARATOR);
return entries;
}