Created
March 29, 2012 02:51
-
-
Save ryanswanstrom/2232746 to your computer and use it in GitHub Desktop.
Here are 2 functions to sort a Map by the value instead of the key.
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
/** | |
* This method will return a sorted Map | |
* @param unsortMap | |
* @return | |
*/ | |
private static Map<String, Integer> sortMapByValue(Map<String, Integer> unsortMap) { | |
List<Map.Entry<String, Integer>> list = new LinkedList(unsortMap.entrySet()); | |
//sort list based on comparator | |
Collections.sort(list, new Comparator() { | |
@Override | |
public int compare(Object o1, Object o2) { | |
return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue()); | |
} | |
}); | |
//put sorted list back into a map | |
Map<String, Integer> sortedMap = new LinkedHashMap(); | |
for (Map.Entry<String, Integer> entry : list) { | |
sortedMap.put(entry.getKey(), entry.getValue()); | |
} | |
return sortedMap; | |
} | |
/** | |
* This method will return a sorted List. | |
* | |
* @param unsortMap | |
* @return | |
*/ | |
private static List<Map.Entry<String, Integer>> sortMapByValueForList(Map<String, Integer> unsortMap) { | |
List<Map.Entry<String, Integer>> sortedList = new ArrayList(unsortMap.entrySet()); | |
//sort list based on comparator | |
Collections.sort(sortedList, new Comparator() { | |
@Override | |
public int compare(Object o1, Object o2) { | |
return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue()); | |
} | |
}); | |
return sortedList; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment