Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic Collection Comparator
/**
* By BalusC at: http://stackoverflow.com/a/1814112/1994530
*/
public class GenericComparator implements Comparator<Object> {
private String getter;
public GenericComparator(String field) {
this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
}
public int compare(Object o1, Object o2) {
try {
if (o1 != null && o2 != null) {
o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);
o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]);
}
} catch (Exception e) {
// If this exception occurs, then it is usually a fault of the developer.
throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e);
}
return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable<Object>) o1).compareTo(o2));
}
}
// Sort on "phone" field of the Contact bean.
Collections.sort(contacts, new GenericComparator("phone"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.