Sorting the Map<Key,Value> in descending order based on the value

Viewed 108777

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

I am using map interface to read from a file and then store the values in that as a key value pair. The file format is as follows

 A 34
 B 25
 c 50

I will read the datas from this file and store that as a key value pair and then I will display this to the user. My requirement is to display the results in this format

C 50
A 34
B 25

Thus I need to sort the map in descending order of the value. So that I will be able to display these as my result .. I have read about this and find the below code

static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }

I hope this is gonna sort the values in ascending order, I just want to know whether this approach is correct or some other effective approach will be helpful for me ?

2 Answers
Related