Comparable(I) and Comparator(I) Interface in Java
Comparable(I) and Comparator(I) in Java are very useful for sorting the collection of objects
Comparable(I) — if you want natural sorting order then you should go with comparable interface.
-present in java.lang.Comparable
-method present in public int compareTo(Object obj);
-String and All Wrapper Class by Default implements Comparable(I).
For Custom Class -
If you want natural sorting then you need to implements Comparable(I).
Example
public class Employee implements Comparable<Employee> {
private int id;
//setter getter
private String name;
public int getId() {
return id;
}public Employee(int id,String name ) {
this.id = id;
this.name=name;}@Override
public int compareTo(Employee emp) {
return (this.id — emp.id);
}}Now when we execute the above snippet for Arrays sorting of Employees and print it, here is the output.
Default Sorting of Employees list:
[[id=1, name=Pankaj], [id=5, name=Lisa], [id=10, name=Mikey]]
Comparator(I) -If you want custom sorting then you should go with Comparator(I).
- Comparator interface is present in java.util package
- method present in
*public int compare(Object o1, Object o2)
*boolean equals(Object obj);
Employee
public class Employee implements Comparable<Employee> {
private int sal;
private String name;
public Employee(int sal, String name) {
super();
this.sal = sal;
this.name = name;
}
@Override
public String toString() {
return “Employee [sal=” + sal + “, name=” + name + “]”;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Employee o) {
// TODO Auto-generated method stub
return o.getName().compareTo(getName());
}}
Custom Logic
public class CustomExample implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
if (o1.getSal() > o2.getSal())
return 1;
if (o1.getSal() < o2.getSal())
return -1;
if (o1.getSal() == o2.getSal()) {
o1.getName().compareTo(o2.getName());}
return 0;
}}
Testing
package example.Core.testing;
public class ExampleTesting {
public static void main(String[] args) {
Employee emp1 = new Employee(1500, “SANJAY”);
Employee emp2 = new Employee(1900, “Raj”);
Employee emp3 = new Employee(1500, “Taj”);
Employee emp4 = new Employee(1900, “xyz”);
Employee emp5 = new Employee(1700, “SAN”);
Employee emp6 = new Employee(1600, “Zaj”);
List<Employee> list = new ArrayList<>();
list.add(emp1);
list.add(emp2);
list.add(emp3);
list.add(emp4);
list.add(emp5);
list.add(emp6);
Collections.sort(list, new CustomExample());
for (Employee employee : list) {
System.out.println(employee);
}}}