Java Sort By Map Value

Posted: November 17, 2009 in Java, Programming, Software
Tags: , , , , ,

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;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s