Sunday, December 10, 2017

Sorting Objects | Comparator



Comparator interface is used to provide user defined sorting of java objects. It helps you create multiple ordering sequences. With comparable interface you can define only single sorting criteria but with Comparator interface you can define multiple sorting criteria. You just need to create separate classes implementing Comparator interface, like below example classes.
Sort student objects by student name:

public class NameComarator implements Comparator<Student> {
       @Override
       public int compare(Student o1, Student o2) {
             return o1.getName().compareTo(o2.getName());
       }
}

Sort student objects by student roll number:
public class RollNumberComparator implements Comparator<Student> {
       @Override
       public int compare(Student o1, Student o2) {
             if (o1.getRollNum() < o2.getRollNum()) {
                    return -1;
             } else if (o1.getRollNum() == o2.getRollNum()) {
                    return 0;
             } else
                    return 1;
       }
}

public class Student {

       private String name;
       private String level;
       private int rollNum;

       public String getName() {
             return name;
       }

       public void setName(String name) {
             this.name = name;
       }

       public String getLevel() {
             return level;
       }

       public void setLevel(String level) {
             this.level = level;
       }

       public int getRollNum() {
             return rollNum;
       }

       public void setRollNum(int rollNum) {
             this.rollNum = rollNum;
       }

}

Comparator interface has two methods, compare() and equals(). Each class has default implementation of equals() method available from Object class, so if you think overriding equals() method is not required, you can skip it. But you must have to provide implementation of compare() method. Compare method accept two objects and returns -1, 0 or 1 according to sorting/ordering logic defined.

Pros & Cons:   
  • Comparator interface allows you to compare two objects.
  • For using comparator, you need to create new class for each implementation and comparing criteria.
  • It provides very loose coupling, If in future you want to any other criteria for comparing your objects you don’t have to modify your existing class.
  • You can provide multiple comparison logic for your class.
  • You don’t require actual code of a class you want to compare. It helps you writing comparison logic for third party library classes too.

0 comments:

Post a Comment