Using collections.sort
approach:
- convert HashMap to List
- sort list using
custom comparator
- then create list of
key
(sorted order based on their values)
code:
// function to sort hashmap by values
public static List sortByValue(HashMap < String, Integer > hm) {
// Create a list from elements of HashMap
List < Map.Entry < String, Integer > > list =
new LinkedList < Map.Entry < String, Integer > > (hm.entrySet());
// Sort the list
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());
}
});
// put data from sorted list to hashmap
List < String > temp = new ArrayList < String > ();
for (Map.Entry < String, Integer > aa: list) {
temp.add(aa.getKey());
}
return temp;
}