wellnwill Marathahalli Bangalore

To sort data with Comparator

Comparator interface:

  • We use this interface to compare the object by using various properties.
  • We have to write a separate class by implementing Comparator interface and have to override the below methods. 1. public boolean equals(Object obj) 2. public int compare(Object ob1,object ob2)
  • This interface is present in java.util package.

    In compare() method we need to typecast the value from Object type to corresponding type and then we can do comparision.

    import java.util.*;
    class Person 
    {
     int id;
     String name;
     int sal;
     
     Person(int id,String name,int sal)
     {
      this.id=id;
      this.name=name;
      this.sal=sal;
     }
       public String toString()
     {
      return id+".."+name+".."+sal;
     }
    }
    
    
    class SalComparator implements Comparator
    {
     public int compare(Object o1,Object o2)
     {
      if(o1 instanceof Person && o2 instanceof Person)
      {
       Person p1=(Person)o1;
       Person p2=(Person)o2;
       if(p1.sal==p2.sal)  
        return 0;  
       else if(p1.sal>p2.sal)  
        return 1;  
       else  
        return -1;  
      }
      return 0;
    }
    }
    
    
    class NameComparator implements Comparator
    {
     public int compare(Object o1,Object o2)
     {
      if(o1 instanceof Person && o2 instanceof Person)
      {
       Person p1=(Person)o1;
       Person p2=(Person)o2;
       return p1.name.compareTo(p2.name); //ASC
       //return p2.name.compareTo(p1.name); DESC
      }
      return 0;
     }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    public class Test277
    {
     public static void main(String args[])
     {
     Person p[]=new Person[4];
     p[0]=new Person(4,"John",20000);
     p[1]=new Person(2,"David",26000);
     p[2]=new Person(3,"Mac",22000);
     p[3]=new Person(1,"Robert",21000);
     
     for(Person p1:p)
     {
     System.out.println(p1);
     }
     System.out.println("........");
     System.out.println("Sorting by Salary");
     Arrays.sort(p,new SalComparator());
     
     for(Person p1:p)
     {
     System.out.println(p1);
     }
     System.out.println("........");
     System.out.println("Sorting by Name");
     Arrays.sort(p,new NameComparator());
     
     for(Person p1:p)
     {
     System.out.println(p1);
     }
     }
    }
    
Footer with Map

Top