Drop Down

Thursday, January 17, 2019

COMPARATOR::: Sort Employee Object using employee id

package comparator.Emp;
//When we are not allowed to change Class Employee code (i.e we can't implement Comparable)
//We use comparator Interface.
public class Employee
{
int empid;
String name;
int deptid;
public Employee(int empid, String name, int deptid)
{
super();
this.empid = empid;
this.name = name;
this.deptid = deptid;
}
/*@Override
public String toString() {
return "Empid=" + empid + ", Name=" + name + ", Deptid=" + deptid;
}*/


}
==========================================
package comparator.Emp;
import java.util.*;
//Sort the Employeee Class using empid -- Use Comparator
public class Emp_Runner {

public static void main(String[] args) 
{
Employee emp1  = new Employee(111,"Amit",549);
Employee emp2  = new Employee(674,"Dinesh",549);
Employee emp3  = new Employee(352,"Manohar",667);
Employee emp4  = new Employee(642,"Dilip",889);
Employee emp5  = new Employee(133,"Govind",667);
 
List list = new ArrayList();
list.add(emp1);
list.add(emp2);
list.add(emp3);
list.add(emp4);
list.add(emp5);
 
Comparator comp = new Emp_Comp(); //Comparator is Interface so we can't instanciate it.
Collections.sort(list,new Emp_Comp());  //call to compare() .... from here
 
Iterator itr = list.iterator();
while(itr.hasNext())
{
Employee emp = (Employee) itr.next();
System.out.println("Empid=" + emp.empid + ", Name=" + emp.name + ", Deptid=" + emp.deptid);
 
}
 
 
}


}
==========================================
package comparator.Emp;

import java.util.Comparator;

public class Emp_Comp implements Comparator<Employee>
{

@Override
public int compare(Employee e1, Employee e2) 
{
if(e1.empid > e2.empid)
{
return 1;
}
else return 
-1;
}

}
============================================
============================================

No comments:

Post a Comment

Java 8 Notes Pics