Created
January 14, 2019 05:29
-
-
Save ohdoking/2bdda60146b14aeaf9fb41a6870f54f6 to your computer and use it in GitHub Desktop.
sort by value in Map in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function to sort hashmap by values | |
public static HashMap<String, Integer> 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 (o1.getValue()).compareTo(o2.getValue()); | |
} | |
}); | |
// put data from sorted list to hashmap | |
HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); | |
for (Map.Entry<String, Integer> aa : list) { | |
temp.put(aa.getKey(), aa.getValue()); | |
} | |
return temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment