The below example shows Java program to sort a Map by values in ascending and descending order, you can see that it’s so easy to sort the Map.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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; } |