I need a comparator for a TreeMap. Should I write this anonymously in the constructor for my TreeMap? How else could I write my comparator. Currently, Java does not like my code (can I do this anonymously?):
SortedMap<String, Double> myMap =
new TreeMap<String, Double>(new Comparator<Entry<String, Double>>()
{
public int compare(Entry<String, Double> o1, Entry<String, Double> o2)
{
return o1.getValue().compareTo(o2.getValue());
}
});
- Can I do the above anonymously?
- How else could I do this?
- I want to sort myMap by the Value not the Key
You can not sort TreeMap on values.
To provide sort on values you will need SortedSet. Use
To give you an example
Output: