Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java Comparator Example

  1. package examples;
  2.  
  3. /*
  4. Java Comparator example.
  5. This Java Comparator example describes how java.util.Comparator
  6. interface is implemented to compare Java custom class objects.
  7.  
  8. This Java Comparator is passed to Collection's sorting method
  9. (for example Collections.sort method) to perform sorting of Java custom
  10. class objects.
  11.  
  12. */
  13.  
  14. import java.util.*;
  15.  
  16. /*
  17. java.util.Comparator interface declares two methods,
  18. 1) public int compare(Object object1, Object object2) and
  19. 2) boolean equals(Object object)
  20. */
  21.  
  22. /*
  23. We will compare objects of the Employee class using custom comparators
  24. on the basis of employee age and name.
  25. */
  26.  
  27. class Employee{
  28.    
  29.     private int age;    
  30.     private String name;
  31.    
  32.     public void setAge(int age){
  33.         this.age=age;    
  34.     }
  35.    
  36.     public int getAge(){
  37.         return this.age;    
  38.     }
  39.    
  40.     public void setName(String name){
  41.         this.name=name;    
  42.     }
  43.    
  44.     public String getName(){    
  45.         return this.name;    
  46.     }
  47. }
  48.  
  49. /*
  50. User defined Java comparator.
  51. To create custom java comparator, implement Comparator interface and
  52. define compare method.
  53.  
  54. The below given comparator compares employees on the basis of their age.
  55. */
  56.  
  57. class AgeComparator implements Comparator{
  58.    
  59.     public int compare(Object emp1, Object emp2){
  60.    
  61.         /*
  62.          * parameter are of type Object, so we have to downcast it
  63.          * to Employee objects
  64.          */
  65.        
  66.         int emp1Age = ((Employee)emp1).getAge();        
  67.         int emp2Age = ((Employee)emp2).getAge();
  68.        
  69.         if(emp1Age > emp2Age)
  70.             return 1;
  71.         else if(emp1Age < emp2Age)
  72.             return -1;
  73.         else
  74.             return 0;    
  75.     }
  76.    
  77. }
  78.  
  79. /*
  80. The below given comparator compares employees on the basis of their name.
  81. */
  82.  
  83. class NameComparator implements Comparator{
  84.  
  85.     public int compare(Object emp1, Object emp2){    
  86.  
  87.         //parameter are of type Object, so we have to downcast it to Employee objects
  88.        
  89.         String emp1Name = ((Employee)emp1).getName();        
  90.         String emp2Name = ((Employee)emp2).getName();
  91.        
  92.         //uses compareTo method of String class to compare names of the employee
  93.         return emp1Name.compareTo(emp2Name);
  94.    
  95.     }
  96.  
  97. }
  98.  
  99. /*
  100. This Java comparator example compares employees on the basis of
  101. their age and name and sort them in that order.
  102. */
  103.  
  104. public class JavaComparatorExample{
  105.    
  106.     public static void main(String args[]){
  107.        
  108.         //Employee array which will hold employees
  109.         Employee employee[] = new Employee[2];
  110.        
  111.         //set different attributes of the individual employee.
  112.         employee[0] = new Employee();
  113.         employee[0].setAge(40);
  114.         employee[0].setName("Joe");
  115.        
  116.         employee[1] = new Employee();
  117.         employee[1].setAge(20);
  118.         employee[1].setName("Mark");
  119.        
  120.         System.out.println("Order of employee before sorting is");
  121.         //print array as is.
  122.         for(int i=0; i < employee.length; i++){
  123.             System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge());
  124.         }
  125.        
  126.         /*
  127.         Sort method of the Arrays class sorts the given array.        
  128.         Signature of the sort method is,        
  129.         static void sort(Object[] object, Comparator comparator)
  130.        
  131.         IMPORTANT: All methods defined by Arrays class are static. Arrays class        
  132.         serves as a utility class.
  133.         */
  134.        
  135.         //Sorting array on the basis of employee age by passing AgeComparator
  136.         Arrays.sort(employee, new AgeComparator());
  137.         System.out.println("\n\nOrder of employee after sorting by employee age is");
  138.        
  139.         for(int i=0; i < employee.length; i++){
  140.             System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge());
  141.         }
  142.        
  143.         //Sorting array on the basis of employee Name by passing NameComparator
  144.         Arrays.sort(employee, new NameComparator());
  145.        
  146.         System.out.println("\n\nOrder of employee after sorting by employee name is");    
  147.         for(int i=0; i < employee.length; i++){
  148.             System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge());
  149.         }
  150.    
  151.     }
  152.  
  153. }
  154.  
  155. /*
  156. OUTPUT of the above given Java Comparable Example would be :
  157. Order of employee before sorting is
  158. Employee 1 name :: Joe, Age :: 40
  159. Employee 2 name :: Mark, Age :: 20
  160. Order of employee after sorting by employee age is
  161. Employee 1 name :: Mark, Age :: 20
  162. Employee 2 name :: Joe, Age :: 40
  163. Order of employee after sorting by employee name is
  164. Employee 1 name :: Joe, Age :: 40
  165. Employee 2 name :: Mark, Age :: 20
  166. */
Your rating: None Average: 4.3 (104 votes)
Share this
Anonymous's picture

*

*
Anonymous's picture

nice

nice
Anonymous's picture

You could also use generics,

You could also use generics, "class NameComparator implements Comparator". This way there is no need to cast objects.
Anonymous's picture

"It's the non-diet diet.

"It's the non-diet diet. However, just a few high-income women can afford it, because they are too expensive, especially financial crisis. A. After brunch, the resort line was shown. "Under Pressure" chant e par David Bowie et par Queen dans les ann es 80, et "Ice Ice Baby" de Vanilla Ice (Top 10 en 1991)..
Anonymous's picture

I have also taken a liking to

I have also taken a liking to the "Bardot" model. The bag goes with all clothes. Kate Middleton : La duchesse de Cambridge nomm茅e personnalit茅 la mieux habill茅e de Grande-BretagneKate Middleton : La duchesse de Cambridge s'habille aux couleurs 茅cossaisesLa reine Elizabeth II re莽oit un BAFTA d'honneur pour son r么le de James Bond girlElizabeth II : Un Bafta d'honneur pour son interpr茅tation aux JO de LondresMort de Margaret Thatcher : les grosses boulettes des m茅diasLOOK : Au pays de l'or noir c. An abundance of wonderful deals to them should view in just the right points of interest.
Anonymous's picture

Bottom line is that I don

Bottom line is that I don hate U2, I just want them to go away forever and stop making horrible horrible music that makes me want to puke no matter what kind of mood I in.. sex drugssex pills wholesalesex pillssex pills for womenfemale sex pillswoman sex drive pillsmale sex pillssex delay spraysex toysadult sex toysbest sex toyscondomfemale condomcondom sexbest condomsPilatoryweight loss productsbest weight loss productssex drive pillsbest sex pillstop weight loss productsmale sex endurance pillsbest male sex pillsherbal sex pillherbal sex pill for menherbal sex pills for women Leone offers its clientele luxuriously tailored suits from a wide variety of international designers. As a sister to a gay brother, Anne Hathaway wishes gay marriage was legal throughout the entire United States. Moses Malone pour donner l'Air Force 1 grand temp茅rament, la durabilit茅 des chaussures inspir茅es par Jamaal Wilkes,Chaussures Mitchell Thompson dans le meilleur style de refl茅ter le coursAir Force OneLe geste h茅ro茂que, mais la continuit茅 de la baskets dans le style de Bobby Jones terrain de golf dans la meilleure preuve.
Anonymous's picture

ルイヴィトン バッグ 白あんの甘さと、あんずのすっぱさが

ルイヴィトン バッグ 白あんの甘さと、あんずのすっぱさが よく合うんだよ。 ルイヴィトン バッグ 唇の左下にクリスタルが一粒輝いて。 ルイヴィトン 新作 努力する気持ちはありますよくわからないことが多いので、アパレル関係の職業の方などお詳しい方は、最終的にこの夢に近づいていける道を是非教えてください説明不足な部分もあるとおもうので、何かありましたら回答してください補足しますこんばんは!。 MONTBLANC 今回の公演には2008-09シーズンのエキシビジョンプログラムの『ゴールド』とともに、「サプライズ演技」を披露する可能性がある。 ミュウミュウ 公式 バーバリー ブリットは、ラフなエレガンスをカジュアルなアイテムで表現したコレクション。

Post new comment