Java Comparator Interface

Comparater Interface:
Java Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequence. You can sort the elements on the basis of any data member, for example marks, name or anything else.

Code:

  1. class Student{    
  2. int marks;    
  3. String name;      
  4. Student(int marks,String name){    
  5. this.marks=marks;    
  6. this.name=name;      
  7. }    
  8. }  
  9.   
  10. import java.util.*;    
  11. class marksComparator implements Comparator{    
  12. public int compare(Object o1,Object o2){    
  13. Student s1=(Student)o1;    
  14. Student s2=(Student)o2;    
  15.     
  16. if(s1.marks==s2.marks)    
  17. return 0;    
  18. else if(s1.marks>s2.marks)    
  19. return 1;    
  20. else    
  21. return -1;    
  22. }    
  23. }   
  24.   
  25.   
  26. import java.util.*;    
  27. class NameComparator implements Comparator{    
  28. public int compare(Object o1,Object o2){    
  29. Student s1=(Student)o1;    
  30. Student s2=(Student)o2;    
  31.     
  32. return s1.name.compareTo(s2.name);    
  33. }    
  34. }  
  35.   
  36. //Main class  
  37.   
  38. import java.util.*;    
  39. import java.io.*;    
  40.     
  41. class ComparatorDemo{    
  42. public static void main(String args[]){    
  43.     
  44. ArrayList al=new ArrayList();    
  45. al.add(new Student(70,"Sujan"));    
  46. al.add(new Student(80,"Shakil"));    
  47. al.add(new Student(85,"Shimul"));    
  48.     
  49. System.out.println("Sorting by Name...");    
  50.     
  51. Collections.sort(al,new NameComparator());    
  52. Iterator itr=al.iterator();    
  53. while(itr.hasNext()){    
  54. Student st=(Student)itr.next();    
  55. System.out.println(st.marks+" "+st.name);    
  56. }    
  57.     
  58. System.out.println("sorting by marks...");    
  59.     
  60. Collections.sort(al,new marksComparator());    
  61. Iterator itr2=al.iterator();    
  62. while(itr2.hasNext()){    
  63. Student st=(Student)itr2.next();    
  64. System.out.println(st.marks+" "+st.name);    
  65. }    
  66.     
  67.     
  68. }    
  69. }    
Share:

0 Comments:

Post a Comment