Im using the following code to create a hashmap and then sort the values in the hashmap by using a treemap and a comparator. However, the output is rather unexpected. So any th
The Java Doc of TreeMap
clearly states that:
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys
we should not violate this rule by using TreeMap
to sort by values.
However to sort by values, we can do the following:
LinkedList
of entries of the map
Collection.sort
to sort the entriesLinkedHashMap
: keeps the keys in the order they are inserted, which is currently sorted on natural ordering. Return the LinkedHashMap
as the sorted map
.
public static Map sortByValues(Map map){
List> entries = new LinkedList>(map.entrySet());
Collections.sort(entries, new Comparator>() {
@Override
public int compare(Entry o1, Entry o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map sortedMap = new LinkedHashMap();
for(Map.Entry entry: entries){
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
Reference: Sorting Map by value