Skip to content

Instantly share code, notes, and snippets.

@MiguelCatalan
Created July 26, 2015 15:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MiguelCatalan/ff217559c7206df2605a to your computer and use it in GitHub Desktop.
Save MiguelCatalan/ff217559c7206df2605a to your computer and use it in GitHub Desktop.
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