Monday 11 July 2016

Java Object sorting example (Comparable and Comparable)

     In this post, you can learn how to sort Java object specially ArrayList with custom class as generics using Comparable and Comparator interface. In ArrayList sorting with datatype as generics then no need to use comparable and comparator interface, you can use directly Collections.sort(list) methods.

1) Sort an Array
       
         Use Arrays.sort() method to sort an array. See the below example,

               String[] departments = new String[] {"IT", "Engineering", "Support", "Sales"};
               Arrays.sort(departments);
               for (String dept : departments) {
                     System.out.println(dept);
               }

    output : Engineering
                IT
                Sales
                Support


2) Sort an ArrayList without using Comparable or Comparator

         If you want to sort an ArrayList using datatype as Generics then directly you can pass the arraylist parameter in Collections sort method.
    Example,

            List<String> list = Arrays.asList("IT", "Engineering", "Support", "Sales");
            Collections.sort(list);
            //after sorting
            for (String dept : list) {
                  System.out.println("depts : "+ dept);
            }

output : Engineering
            IT
            Sales
            Support



3) Sort an ArrayList of custom objects by Property (Using Comparable interface)

          If you are sorting the custom objects of ArrayList without using Comparable interface, you will get exception, see below code.
     
               public class Employee {
                      private int id;
                      private String name;
                      public int getId () {
                             return id;
                      }
                      public String getName () {
                             return name;
                      }
                      public Employee (int id, String name) {
                              this.id = id;
                              this.name = name;
                      } 

Sorting Employee class objects,

                 Employee[] emp = new Employee[3];
                 emp[0] = new Employee (1, "Mahesh");
                 emp[1] = new Employee (2, "Kiran");
                 emp[2] = new Employee (3, "Rajesh");
                 
                 List<Employee> list = new ArrayList<Employee>();
                 list.add(emp[0]);
                 list.add(emp[1]);
                 list.add(emp[2]);

                 Collections.sort(list);
            
                 for (Employee e : list) {
                          System.out.println(e);
                 }

 when you try to run this code , it throws Run time exception :--
       Exception in thread "main" java.lang.ClassCastException.

      To sort the custom object based on property then you can use any one Comparable or Comparator interface. In the above Employee class, you can implement with Comparable interface and implement compareTo() method. Keep sorting logic in compareTo() method. See the Employee class.

              public class Employee implements Comparable<Employee> {
                      
                      private int id;
                      private String name;

                      public int getId () {
                             return id;
                      }

                      public String getName () {
                             return name;
                      }
    
                      public Employee (int id, String name) {
                              this.id = id;
                              this.name = name;
                      } 

                      @Override
                      public int compareTo (Employee emp) {
                              return this.id - (Integer)emp.getId();
                      }

          The compareTo(Object arg) method returns the negative integer or zero or positive integer, If it returns the negative integer then this object is less than passed argument, returns zero then this object is equal to passed argument, returns positive integer then this object is greater than passed argument.

     Sorting the above Employee class based on id property using ArrayList is as follows,
  
                    Employee[] emp = new Employee[3];
                    emp[0] = new Employee (3, "Mahesh");
                    emp[1] = new Employee (1, "Kiran");
                    emp[2] = new Employee (5, "Rajesh");
                 
                    List<Employee> list = new ArrayList<Employee>();
                    list.add(emp[0]);
                    list.add(emp[1]);
                    list.add(emp[2]);

                    Collections.sort(list);
            
                    for (Employee e : list) {
                          System.out.println(e.getName());
                    }
  
output :- Kiran
             Mahesh
             Rajesh 


4) Sort an ArrayList of custom objects by Property (Using Comparator interface)

               Using Comparable interface, we can sort single property and that should be an integer type. If you can sort the ArrayList based on multiple properties then use Comparator interface. In order to implement the Comparator interface, to implement the compare(Object obj1, Object obj2) methdod of Comparator interface.
               See the below Employee class,

                   public class Employee implements Comparable<Employee> {
                      
                           private int id;
                           private String name;

                           public int getId () {
                                  return id;
                           }

                           public String getName () {
                                  return name;
                           }
    
                           public Employee (int id, String name) {
                                   this.id = id;
                                   this.name = name;
                           } 

                           @Override
                           public int compare(Employee emp1, Employee emp2) {
                                   return emp1.getName().compareTo(emp2.getName());
                           }

 Sorting the above Employee class based on multiple property using ArrayList is as follows,
  
                    Employee[] emp = new Employee[3];
                    emp[0] = new Employee (3, "Mahesh");
                    emp[1] = new Employee (1, "Kiran");
                    emp[2] = new Employee (5, "Rajesh");
                 
                    List<Employee> list = new ArrayList<Employee>();
                    list.add(emp[0]);
                    list.add(emp[1]);
                    list.add(emp[2]);

                    Collections.sort(list, new Emplyee());
            
                    for (Employee e : list) {
                          System.out.println(e.getName());
                    }
         
         
output :- Kiran
             Mahesh
             Rajesh 


Related Post : --
Difference between Comparable & Comparator Interface in Java 

No comments:

Post a Comment