Sorting of employee using Comprator and Comprable







  Here   in  this   example    we   have    sort  Employee class  according to there age  and
 Student class  according to there age. But  for  sorting Employee we use Comparator while
 sorting Student  used comparable interface




import     java.util.*;
  
public class SortingInterface {


public static void main(String args[]){
        List  ls = new    ArrayList ();
         
                       
                      ls.add(new Employee("Ramu",33));
                      ls.add(new Employee("Bhirkuti",34));
                      ls.add(new Employee("Banku",35));
               
                        Collections.sort(ls,new  Comparator(){

@Override
    public int compare(Employee o1, Employee o2) {
// TODO Auto-generated method stub
   return  Integer.valueOf(o1.getAge()).compareTo(o2.getAge());
}});
                      System.out.println("Sorting Using Comprator Interface");
             
                    for(Employee  i :ls){
             
              System.out.print(i.getAge());
              System.out.print(i.getName());
              System.out.println();
             
              }
             
             
              System.out.println("Sorting Using Comprable Interface");
              ArrayList al=new ArrayList();  
              al.add(new Student(101,"Pandu",15));  
              al.add(new Student(106,"Guddu", 17));  
              al.add(new Student(105,"Pinku", 20));  
               
              Collections.sort(al);  
              for(Student st:al){  
              System.out.println(st.rollno+" "+st.name+" "+st.age);  
              }  
             
                       
                       
   }


}

  Supporting  Classes are  

   

 Employee


public class Employee {
   private  String   Name;
   private  int   age;
   public String getName() {
return Name;
}


public void setName(String name) {
Name = name;
}


public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}


   public  Employee(String  name , int Age){
   
   
      this.Name=name;
      this.age=Age;
   
   }
}


  Student 


class Student implements Comparable{  
int rollno;  
String name;  
int age;  
Student(int rollno,String name,int age){  
this.rollno=rollno;  
this.name=name;  
this.age=age;  
}  
  
public int compareTo(Student st){  
if(age==st.age)  
return 0;  
else if(age>st.age)  
return 1;  
else  
return -1;  
}  
}  


 The   programme   output   will be  Like this .


Sorting Using Comprator Interface
33Ramu
34Bhirkuti
35Banku
Sorting Using Comprable Interface
101 Pandu 15
106 Guddu 17
105 Pinku 20

Sorting of employee using Comprator and Comprable  Sorting  of employee using   Comprator  and  Comprable Reviewed by Mukesh Jha on 11:59 PM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.