Skip to content

Instantly share code, notes, and snippets.

@ohdoking
Created January 14, 2019 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohdoking/2bdda60146b14aeaf9fb41a6870f54f6 to your computer and use it in GitHub Desktop.
Save ohdoking/2bdda60146b14aeaf9fb41a6870f54f6 to your computer and use it in GitHub Desktop.
sort by value in Map in Java
// 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