Created
July 26, 2015 15:53
-
-
Save MiguelCatalan/ff217559c7206df2605a to your computer and use it in GitHub Desktop.
Generic Collection Comparator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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