DSA using Java - Sorting Objects


Advertisements

Java objects can be sorted easily using java.util.Arrays.sort() method. Consider the following example.

ObjectSortingDemo.java

package com.tutorialspoint.simplesort;

public class ObjectSortingDemo {

   public static void main(String[] args){

      /* array of String objects */
      String[] employees 
      = new String[] {"Robert", "Paul","John","Micheal" };

      System.out.println("Unsorted Array : " 
         + Arrays.toString(employees));

      /* sort array in lexicographical order */
      Arrays.sort(employees);       

      System.out.println("Sorted Array : " 
         + Arrays.toString(employees));
      System.out.println();
   }
}   

If we compile and run the above program then it would produce following result:

Unsorted Array : [Robert, Paul, John, Micheal]
Sorted Array : [John, Micheal, Paul, Robert]

Using Comparable interface

In order to sort an object its class can implement java.lang.Comparable interface. Consider the following code.

Employee.java

package com.tutorialspoint.simplesort;

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

   public Employee (int employeeId,String name, String department){
      this.employeeId = employeeId;
      this.name = name;
      this.department = department;
   }

   @Override
   public int compareTo(Employee employee) {
      return employeeId - employee.employeeId;
   }

   public String getName(){
      return name;
   }

   public String getDepartment(){
      return department;
   }

   @Override
   public String toString() {
      return "\n[ " + employeeId
         +"," + name
         +"," + department
         +" ]";
   }    
}

Here Employee class implements java.lang.Comparable interface and have a method compareTo(). Array.sort() uses mergesort algorithm and uses this compareTo() method to compare two objects in order to the sort the object array passed as argument.

ObjectSortingDemo.java

public class ObjectSortingDemo {

   public static void main(String[] args){

      /* Use of Arrays.sort() method to sort array */
      Employee[] employeesObjects = new Employee[] {
         new Employee(100, "Robert", "Finance"),
         new Employee(30, "Paul", "Finance"),
         new Employee(50, "John", "Finance"),
         new Employee(12, "Micheal", "Finance")
      };

      System.out.println("Unsorted Array : " 
         + Arrays.toString(employeesObjects));
      Arrays.sort(employeesObjects);  
      System.out.println();	  
      System.out.println("Sorted Array by id: " 
         + Arrays.toString(employeesObjects));      
   }
}   

If we compile and run the above program then it would produce following result −

Unsorted Array : [
[ 100,Robert,Finance ],
[ 30,Paul,Finance ],
[ 50,John,Finance ],
[ 12,Micheal,Finance ]]

Sorted Array by id: [
[ 12,Micheal,Finance ],
[ 30,Paul,Finance ],
[ 50,John,Finance ],
[ 100,Robert,Finance ]]

Using Comparator interface

Using java.util.Comparator interface provides us a precise control over the sorting of an objects. As we've seen in previous example, we've set a criteria by implmenting the java.lang.Comparable interface that employees should be sorted based on compareTo() method within the class. Using Comparator class, we can set a criteria without modifying a class if it has not implemented the comparable interface. Consider the following code.

Employee.java

package com.tutorialspoint.simplesort;

public class Employee {
    
   private int employeeId;
   private String name;
   private String department;

   public Employee (int employeeId,String name, String department){
      this.employeeId = employeeId;
      this.name = name;
      this.department = department;
   }   

   public String getName(){
      return name;
   }

   public String getDepartment(){
      return department;
   }

   @Override
   public String toString() {
      return "\n[ " + employeeId
         +"," + name
         +"," + department
         +" ]";
   }    
}

Define a comparator which can compare two employees based on their name.

EmployeeNameComparator.java

package com.tutorialspoint.simplesort;

import java.util.Comparator;

public class EmployeeNameComparator implements Comparator<Employee> {
   @Override
   public int compare(Employee employee1, Employee employee2) {
      return employee1.getName().compareTo(employee2.getName());
   }    
}

Here EmployeeNameComparator class implements java.util.Comparator interface and have a method compare(). Array.sort() uses mergesort algorithm and uses this compare() method to compare two objects in order to the sort the object array passed as argument.

ObjectSortingDemo.java

public class ObjectSortingDemo {

   public static void main(String[] args){

      /* Use of Arrays.sort() method to sort array  */
      Employee[] employeesObjects = new Employee[] {
         new Employee(100, "Robert", "Finance"),
         new Employee(30, "Paul", "Finance"),
         new Employee(50, "John", "Finance"),
         new Employee(12, "Micheal", "Finance")
      };

      System.out.println("Unsorted Array : " 
         + Arrays.toString(employeesObjects));
      Arrays.sort(employeesObjects,new EmployeeNameComparator());   
      System.out.println();
      System.out.println("Sorted Array by name: " 
         + Arrays.toString(employeesObjects));      
   }
}   

If we compile and run the above program then it would produce following result −

Unsorted Array : [
[ 100,Robert,Finance ], 
[ 30,Paul,Finance ], 
[ 50,John,Finance ], 
[ 12,Micheal,Finance ]]

Sorted Array by name: [
[ 50,John,Finance ], 
[ 12,Micheal,Finance ], 
[ 30,Paul,Finance ], 
[ 100,Robert,Finance ]]
Advertisements