In my previous post we saw Comparable and it’s implementation. Java provides another way to compare objects. Instead of implementing the comparable interface, we can implement the Comparator interface.

The main difference between these two interfaces is that the comparable interface defines one method compareTo(), which takes one parameter.

The comparator interface defines one method compare() that takes two parameters (of the same type) and returns the comparison of these two objects.

Lets see implementation of comparator

User.java

public class User {
    private String userName;
    private Integer age;
    // getter setter
}

UserComparatorExample.java

public class UserComparatorExample {

    static final Comparator < User > AGEORDER = new Comparator < User > () {
        public int compare(User u1, User u2) {
            // sort in ASC order of age
            return u1.getAge().compareTo(u2.getAge());
        }
    };

    static final Comparator < User > AGEANDNAME = new Comparator < User > () {
        public int compare(User e1, User e2) {
            // sort in DESC order of age
            int dateCmp = e2.getAge().compareTo(e1.getAge());
            if (dateCmp != 0) { // if age are not equal
                return dateCmp;
            } else {
                // if age are equal sort with UserName ASC
                return (e1.getUserName().compareTo(e2.getUserName()));
            }
        }
    };

    public static void main(String[] args) {

        User name[] = {
            new User("Aashish", 12),
            new User("Suman", 12),
            new User("Naveen", 34),
            new User("Ashish", 10),
            new User("Dheepan", 10),
            new User("Satish", 26)
        };
        List < User > names = Arrays.asList(name);
        Collections.sort(names, AGEORDER);
        System.out.println("AGEORDER => " + names);
        Collections.sort(names, AGEANDNAME);
        System.out.println("AGEANDNAME => " + names);
        Collections.sort(names, new AgeComparator());
        System.out.println("AgeComparator => " + names);
    }
}

AgeComparator.java

public class AgeComparator implements Comparator < User > {

    @Override
    public int compare(User e1, User e2) {
        int dateCmp = e1.getAge().compareTo(e2.getAge());
        if (dateCmp != 0) { // if age are not equal
            return dateCmp;
        } else {
            return (e1.getUserName().compareTo(e2.getUserName()));
        }
    }
}

Output:

AGEORDER => [Ashish 10, Dheepan 10, Aashish 12, Suman 12, Satish 26, Naveen 34]
AGEANDNAME => Naveen 34, Satish 26, Aashish 12, Suman 12, Ashish 10, Dheepan 10]
AgeComparator => [Ashish 10, Dheepan 10, Aashish 12, Suman 12, Satish 26, Naveen 34]

Lets break it down:

  • AGEORDER
    1. We created an Comparator object which takes Argument as User.
    2. It implements compare method which takes 2 User object.
    3. Inside compare we define how we need to compare User’s object in this case by age ASC It returns int 0, -1, 1 based on comparison
  • AGEANDNAME
    1. Same as AGEORDER except that it adds extra condition for further sorting if age’s are equal.
  • AgeComparator
    1. The only difference is it’s defined in another class. Just another way to define Comparator

Note:  To sort object in descending order just change order of Obj in compareTo as done in AGEANDNAME

Categories: JAVA

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.