Posts Tagged ‘map’

Java utility method to sort a Map based on map values.

@SuppressWarnings(value = { “unchecked” })
public static List sortByValue(final Map m) {
List keys = new ArrayList();
keys.addAll(m.keySet());
Collections.sort(keys, new Comparator() {
public int compare(Object o1, Object o2) {
Object v1 = m.get(o1);
Object v2 = m.get(o2);
if (v1 == null) {
return (v2 == null) ? 0 : 1;
} else if (v1 instanceof Comparable) {
return ((Comparable) v2).compareTo(v1);
} else {
return 0;
}
}
});
return keys;
}

Advertisements