Comparable is used for single sequence sorting. It is available in java.lang package. By default compareTo method available in Comparator.
Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods.
The Comparable interface has compareTo(T obj) method which is used by sorting methods, you can check any Wrapper, String or Date class to confirm this. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as an argument.
After implementing Comparable interface in Employee class, here is the resulting Employee class.
package com.csi.collectionconcept;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Employee implements Comparable {
int empId;
String empName;
int empAge;
public Employee(int empId, String empName, int empAge) {
super();
this.empId = empId;
this.empName = empName;
this.empAge = empAge;
}
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", empAge=" + empAge + "]";
}
public int compareTo(Employee e1) {
if (empAge == e1.empAge) {
return 0;
}
else if (empAge > e1.empAge) {
return 1;
}
else {
return -1;
}
}
}
public class ComparableConcept {
public static void main(String[] args) {
List employeeList = new ArrayList<>();
employeeList.add(new Employee(121, "JERRY", 21));
employeeList.add(new Employee(122, "TOM", 24));
employeeList.add(new Employee(120, "RABEA", 20));
Collections.sort(employeeList);
employeeList.forEach(emp -> System.out.println(emp));
}
}
Output: Sort By Name Customer [customerId=129, customerName=JERRY, customerAge=25] Customer [customerId=145, customerName=RABEA, customerAge=20] Customer [customerId=126, customerName=TOM, customerAge=23] Sort By Age Customer [customerId=145, customerName=RABEA, customerAge=20] Customer [customerId=126, customerName=TOM, customerAge=23] Customer [customerId=129, customerName=JERRY, customerAge=25] |