public static void main(String args[]) {
Map < String, Integer > map = new HashMap < String, Integer > ();
map.put("A", 34);
map.put("B", 25);
map.put("C", 50);
map.put("D", 50); // "duplicate" value
System.out.println(entriesSortedByValues(map));
}
static < K, V extends Comparable < ? super V >> List < Entry < K, V >> entriesSortedByValues(Map < K, V > map) {
List < Entry < K, V >> sortedEntries = new ArrayList < Entry < K, V >> (map.entrySet());
Collections.sort(sortedEntries, new Comparator < Entry < K, V >> () {
@Override
public int compare(Entry < K, V > e1, Entry < K, V > e2) {
//return e1.getValue().compareTo(e2.getValue()); // if ascending order
return e2.getValue().compareTo(e1.getValue()); // if descending order
}
});
return sortedEntries;
}