I just have a map implementation below to sort the values in descending order and I have used the below implementation.
public static Map<String,Integer> sortByComparator(Map<String,Integer> unsortMap) {
List list = new LinkedList(unsortMap.entrySet());
//sort list based on comparator
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
});
//put sorted list into map again
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
This does the necessary functions.. But I am curious to know whether I will be able to use tree map to sort this by descending order
You won’t, as the TreeMap sorts by key order, and you are sorting by value.