-3

I have key, value pairs. The key is a String and the values are integers. I would want to sort it in descending order so that the element with the highest value appears first.

How do I sort a sorted set in descending order ?

Viraj
  • 5,083
  • 6
  • 35
  • 76

1 Answers1

1

You can do it with TreeMap, for example:

//any not sorted map
Map<String, Integer> map = new HashMap<>();
map.put("567", 567);
map.put("456", 456);
map.put("123", 123);

//create sorted TreeMap with descending sorting
Map<String, Integer> sortedMap = new TreeMap<String, Integer>(Collections.reverseOrder());
sorted.putAll(map);

If you wish to sort it by values, then you can make it so:

private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortedMap) {

    List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortedMap.entrySet());

    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> o1,
                           Map.Entry<String, Integer> o2) {
            return (o2.getValue()).compareTo(o1.getValue());
        }
    });

    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext();) {
        Map.Entry<String, Integer> entry = it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    return sortedMap;
}
Stanislav
  • 27,441
  • 9
  • 87
  • 82