Comparator Interface with example:
Comparator Interface belongs to java.utill package. Comparator is also used to compare the two objects by overriding its inherited int compare(Object o1,Object o2) method.Here I'm going to give example to understand well about Comparator Interface in java.
Create an Employee bean class Employee.java :
public class Employee{
private int eid;
private String ename;
private int age;
public Employee(int eid,String ename,int age) {
this.eid=eid;
this.ename=ename;
this.age=age;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Now create a class EmployeeAgeComparator.java to compare and sort based on ages as below
public class EmplyeeAgeComparator implements Comparator<Employee>
{
@Override
public int compare(Employee o1, Employee o2) {
if(o1.getAge()>o2.getAge())
return 1;
if(o1.getAge()<o2.getAge())
return -1;
if(o1.getAge()==o2.getAge())
return 0;
return 0;
}
}
Create an employee comparator class and call Collections.sort() method to sort values based on age and print values
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.interview.comparatortest.Employee;
public class EmployeeComparator {
public static void main(String args[]){
List<Employee> emp=new ArrayList<Employee>();
emp.add(new Employee(1,"Alfred", 23));
emp.add(new Employee(2,"Ion Bell", 21));
emp.add(new Employee(3,"Clarke",30));
Collections.sort(emp,new EmplyeeAgeComparator());
for(Employee test:emp){
System.out.println("age=="+test.getAge()+"\tname=="+test.getEname()+"\teid=="+test.getEid());
}
}
}
Output :
age==21 name==Ion Bell eid==2
age==23 name==Alfred eid==1
age==30 name==Clarke eid==3