During my free time i thought of experimenting a little bit on a comparator code snippet that i found on GitHubĀ (if i recall well šŸ˜‰ ).

Well we all know that ComparablesĀ are used to sort objects in a collection already provided by java.

But there was this situation i was caught up with, where in, I had to sort objects with alphanumeric data in it. Like for instance, Grades, we could have Grade 1, and Grade 10 and sorting them with the regular ComparableĀ we get results like:

Grade 1
Grade 10
Grade 2

Uh oh! That’s really not what i was looking for, so then i came across a custom comparator that did the work on some String, a list of strings, which i extended to a Class of any type, provided the sorting takes place of a string property.

The jar can be obtained from here. And all you have to do is, in my case, i had an issue sorting grades, therefore, the Grades class looked like this:

public class Grades {
    private String gradeId;
    private String gradeName;

    public String getGradeId() {
    return gradeId;
    public void setGradeId(String gradeId) {
    this.gradeId = gradeId;
    public String getGradeName() {
    return gradeName;
    public void setGradeName(String gradeName) {
    this.gradeName = gradeName;

    // needed for sorting by the custom comparator jar
    public static String getGradeNameMethodName() {
    return "getGradeName";

And we simply call the method to sort as under:

public static List<Grades> getSortedList(List<Grades> gradeList, Class<?> classType, String methodName) {
        Collections.sort(gradeList, new CustomComparator<Grades>(Grades.class, Grades.getGradeNameMethodName()));
        return gradeList;

And that’s the end!..
Happy Coding!
God bless!