public static Map sortMap(Map unsortedMap) {
if (unsortedMap != null && unsortedMap.size() > 1) {
List list = new LinkedList(unsortedMap.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
}
});
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
} else {
return unsortedMap;
}
}
Monday, September 23, 2013
Compose sorted map using an unsorted map's values in Java
You might have unsorted map and sometimes you might need to sort them in some requirements using it's values, not the keys. You can have a util method like this to do it. Make sure the value's class must implement the Comparable interface to mention the sort criteria.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment