Saturday, 21 April 2018


//Object sorting based on empid and based on empname using Comparable Interface........

package collectctiondemo;

public class Employee implements Comparable<Employee>{
int empid;
String empname;
String empaddress;
String email;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpaddress() {
return empaddress;
}
public void setEmpaddress(String empaddress) {
this.empaddress = empaddress;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

// based on empid...................
       @Override
public int compareTo(Employee e) {

if(empid>e.empid)
return 1;
else if(empid<e.empid)
return -1;
else
return 0;
//based  on empname.....................
//return empname.compareTo(e.empname);



}


}

===============================================================================

package collectctiondemo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmployeeMain {
public static void main(String[] args) {
List<Employee> l=new ArrayList<Employee>();
Employee e1=new Employee();
e1.setEmpid(101);
e1.setEmpname("govind");
e1.setEmpaddress("madhubani");
e1.setEmail("govindkhan@gmail.com");
l.add(e1);

Employee e2=new Employee();
e2.setEmpid(107);
e2.setEmpname("ajit");
e2.setEmpaddress("patna");
e2.setEmail("ajitraj@gmail.com");
l.add(e2);

Employee e3=new Employee();
e3.setEmpid(104);
e3.setEmpname("mani");
e3.setEmpaddress("motihari");
e3.setEmail("mani@gmail.com");
l.add(e3);


Employee e4=new Employee();
e4.setEmpid(108);
e4.setEmpname("sanjay");
e4.setEmpaddress("bhagalpur");
e4.setEmail("sanjay@gmail.com");
l.add(e4);


Employee e5=new Employee();
e5.setEmpid(106);
e5.setEmpname("anand");
e5.setEmpaddress("darbhangha");
e5.setEmail("anand@gmail.com");
l.add(e5);
System.out.println("-------------before sorting--------------");
for(Employee emp:l)
{
System.out.println(emp.getEmpid()+" "+emp.getEmpname()+" "+emp.getEmpaddress()+" "+emp.getEmail());
}

Collections.sort(l);

System.out.println("-------------after sorting--------------");
for(Employee emp:l)
{
System.out.println(emp.getEmpid()+" "+emp.getEmpname()+" "+emp.getEmpaddress()+" "+emp.getEmail());
}


}

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


o/p:---------------------

-------------before sorting--------------
101 govind madhubani govindkhan@gmail.com
107 ajit patna ajitraj@gmail.com
104 mani motihari mani@gmail.com
108 sanjay bhagalpur sanjay@gmail.com
106 anand darbhangha anand@gmail.com
-------------after sorting--------------
101 govind madhubani govindkhan@gmail.com
104 mani motihari mani@gmail.com
106 anand darbhangha anand@gmail.com
107 ajit patna ajitraj@gmail.com
108 sanjay bhagalpur sanjay@gmail.com

No comments:

Post a Comment