» » Sort object using comparator

  1. package com.instanceofjava;
  2.  
  3. public class Employee 
  4. {
  5.  
  6.  int id;
  7.  String name;
  8.  
  9.  public Employee(int id, String name) {
  10.  
  11.   this.id=id;
  12.   this.name=name;
  13.  
  14.  }
  15.  
  16. public int getId() {
  17.  
  18. return id;
  19.  
  20. }
  21.  
  22.  public void setId(int id) {
  23.   this.id = id;
  24.  }
  25.  
  26.  public String getName() {
  27.   return name;
  28.  }
  29.  
  30. public void setName(String name) {
  31.  
  32.   this.name = name;
  33.  
  34. }
  35.  
  36. }


  1. class MyEmpComp implements Comparator<Employee >
  2.  
  3.  @Override
  4.  public int compare(Employee e1, Employee e2) {
  5.  
  6.         if(e1.getName() < e2.getName()){
  7.             return 1;
  8.         } else {
  9.             return -1;
  10.         }
  11.  
  12. }
  13.  
  14. }




  1. package com.oops;
  2.  
  3. import java.util.ArrayList;  
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. import java.io.*;  
  8.  
  9. class Main{  
  10.  
  11. public static void main(String args[]){  
  12.  
  13. ArrayList al=new ArrayList();  
  14.  
  15. al.add(new Employee(101,"Indhu"));  
  16. al.add(new Employee(106,"Sindhu"));  
  17. al.add(new Employee(105,"Swathi"));
  18.   
  19. Collections.sort(al,MyEmpComp );  
  20.  
  21. Iterator itr=al.iterator();  
  22.  
  23. while(itr.hasNext()){   
  24.  
  25. Employee st=(Employee)itr.next();  
  26. System.out.println(st.id +" "+st.name );  
  27.  
  28.   }
  29.  
  30.   
  31. }
  32.  
  33.  


Output:
  1. Indhu
  2. Swathi
  3. Sindhu



Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu