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 (71 votes)
Share this
Anonymous's picture

Cool example.

Cool example.
Anonymous's picture

Thanks for your explanation

Thanks for your explanation about Comparator.. I can understand.
Anonymous's picture

very good explanation

very good explanation
Anonymous's picture

Good example.......Thanks

Good example.......Thanks
Anonymous's picture

very Good One.

very Good One.
Anonymous's picture

nice demonstration .. like it

nice demonstration .. like it !
Anonymous's picture

thanks a lot... saved a lot

thanks a lot... saved a lot of time of me..many many thanks :)
Anonymous's picture

Good Example..Thanks a lot

Good Example..Thanks a lot
Anonymous's picture

This is a very good Example

This is a very good Example for Comparator.Kindly provide some more examples by using Hashmaps.
Anonymous's picture

very nice example

very nice example
Anonymous's picture

Good Example

Good Example
Anonymous's picture

thanks cool nice one

thanks cool nice one
Anonymous's picture

To the point and broad

To the point and broad coverage tutorial.......Thanks....... I would like to add that - "The beauty of Comparator is that developer can add many sort sequences."
Anonymous's picture

very good example .u are the

very good example .u are the only person who clears my doubts on this comparator interface
Anonymous's picture

nice and simple to understand

nice and simple to understand example
Anonymous's picture

thanks a lot ...........it

thanks a lot ...........it really helped me
Anonymous's picture

Great Example Thanks a lot

Great Example Thanks a lot
Anonymous's picture

i want to know why we dont

i want to know why we dont implement the equals() method in our comparator class...
Anonymous's picture

Excelent example, simple,

Excelent example, simple, easy thank you
Anonymous's picture

Should implement Comparator

Should implement Comparator and should check for nulls.
Anonymous's picture

Should implement

Should implement Comparator<Employee> and should check for nulls.
Anonymous's picture

+1. This article shows up as

+1. This article shows up as the first Google result for "comparator example". Imagine all the new Java code in the world being copy-pasted from this. I guess I will always have a job.
Anonymous's picture

nice example

nice example
Anonymous's picture

Really nice. Thank you so

Really nice. Thank you so much.
Anonymous's picture

Good and stright example.

Good and stright example. Thanks !
Anonymous's picture

Its vey nice

Its vey nice example...................
Anonymous's picture

Easy to understand :)

Easy to understand :)
Anonymous's picture

very very good example .

very very good example .
Anonymous's picture

nice way to explain

nice way to explain
Anonymous's picture

A clean and clear Example.

A clean and clear Example. good explanation
Anonymous's picture

Hi I have list of Beans with

Hi I have list of Beans with 3 proprties of Employee Bean(name, age, address) I have Taken Address comparator Class shown in below. public class AddressComparitor implements Comparator{ public int compare(Bean bean1,Bean bean2) { int returns=bean1.getAddress().compareTo(bean2.getAddress()); return returns; } } ArrayList list=new ArrayList(); list.add("XXX",25,"12-3-hyd"); list.add("aaa",56,"AD Road-Delhi"); list.add("YYY",23,"45-KKD"); list.add("bbbb",56,"BRRoad-Delhi"); // Sorting.. Colelctions.sort(list,new AddressComparitor()); // Sorting as per Address and display System.out.println("...Sorting as per address........"); for(int i=0;i
Anonymous's picture

nice one...

nice one...
Anonymous's picture

nice one...

nice one...
Anonymous's picture

nice example and easy to

nice example and easy to understood
Anonymous's picture

nice

nice
Anonymous's picture

easy coding

easy coding
Anonymous's picture

easy coding

easy coding
Anonymous's picture

nice one ...thanks :)

nice one ...thanks :)
Anonymous's picture

nice

nice
Anonymous's picture

Really, its a damm good

Really, its a damm good example. I did lots of search, google here and there and i didn't fine anyhting good like this. This is the one which i am not going to forget life long and i can say what is comperator while sleeping also. Bless you
Anonymous's picture

Very excellent to understand

Very excellent to understand this example, I have followed it and tried on my system. Working very well
Anonymous's picture

Really simple yet pawerful

Really simple yet pawerful example wich explains the use of compare() and compareTo() methods.
Anonymous's picture

Hi All, Has anyone executed

Hi All, Has anyone executed the example .Pls execute it...mine is not working..
Anonymous's picture

very good example

very good example
Anonymous's picture

Thanks for Good Example

Thanks for Good Example
Anonymous's picture

good example with explanation

good example with explanation
Anonymous's picture

Thanks for simple and

Thanks for simple and straight, easy to understand example
Anonymous's picture

Nice

Nice
Anonymous's picture

Thanks for a simple and

Thanks for a simple and comprehensive example
Anonymous's picture

Good example.

Good example.

Post new comment