Comparator interface in Java

Java Comparator interface is used to order the objects of a user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element)It provides multiple sorting sequences, i.e., we can sort the elements on the basis of any data member.


This interface is part of java.util package.




We can use Comparator interface in following situations.
  1. Sort the array or list of objects, but NOT in natural order.
  2. Sort the array or list of objects where we can not modify the object’s source code to implement Comparable interface.
  3. Sort same list or array of objects on different fields.
  4. Using group by sort on list or array of objects on different fields.





Employee.java

import java.time.LocalDate;
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String name;
    private LocalDate dob;
    //Getters and Setters
    @Override
    public String toString() {
      return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
    }
}



SortByName.java

import java.util.Comparator;
public class NameSorter implements Comparator<Employee>
{
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getName().compareToIgnoreCase( e2.getName() );
    }
}







Its  use:

//import statements and pvsm
ArrayList<Employee> list = new ArrayList<>();     
list.add(new Employee(2, "Lokesh", LocalDate.now()));
list.add(new Employee(4, "Lokesh", LocalDate.now()));
list.add(new Employee(1, "Alex", LocalDate.now()));
list.add(new Employee(3, "Lokesh", LocalDate.now()));
list.add(new Employee(5, "Charles", LocalDate.now()));
Collections.sort(list, NameSorter);
System.out.println(list);

Output:

[
Employee [id=1, name=Alex, dob=2018-10-30],
Employee [id=2, name=Lokesh, dob=2018-10-30],
Employee [id=3, name=Lokesh, dob=2018-10-30],
Employee [id=4, name=Lokesh, dob=2018-10-30],
Employee [id=5, name=Charles, dob=2018-10-30],
]