How to sort collection using comparable and comparator in java

 Posted On  | Yashwant Chavan 

Let have quick look on sorting technique in java, Using inbuilt sorting API and own customization sorting.

Below example demonstrate the Array list sorting. By default sorting is in ascending order. Collections.sort(list); method sort the list items in ascending order.

Collections.sort(list);

Collections.reverse(list); method sort the list items in descending order.

Collections.reverse(list);

Same as you can sort the arrays also, Let refer the below code snippet, which sort the string array contains name of cities.

String[] cities = new String[] {"Pune","Mumbai", "Chennai", "Bangaleru"};
 Arrays.sort(cities);
 for (String city : cities) {
  System.out.println("city:- " + city);
 }
package com.net.example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SimpleSort {
 public static void main(String[] args) {
  List list = new ArrayList();
  list.add(15);
  list.add(18);
  list.add(4);
  list.add(3);
  list.add(9);
  list.add(12);
  list.add(1);
  System.out.println("Ascending Order Sorting"); 

  Collections.sort(list);
  for (Integer integer : list) {
   System.out.println(integer);
  }

  System.out.println("Descending Order Sorting");

  Collections.reverse(list);
  for (Integer integer : list) {
   System.out.println(integer);
  }  
 }
}

Output of SimpleSort.java

Ascending Order sorting
1
3
4
9
12
15
18
Descending Order sorting
18
15
12
9
4
3
1

Difference Between Comparable and Comparator

Java.lang.Comparable
 To implements comparable interface, class must implement a single method compareTo()
 int a.compareTo(b)
 A comparable object is comparing itself with another object.
 You must modify the class whose instance you want to sort. 
 So that only one sort sequence can be created per class.
 
Java.lang.Comparator
 To implements comparator interface, class must implement a single method compare()
 int compare (a,b)
 A comparator object is comparing two different objects.You build a class separate 
 from class whose instance you want to sort. So that multiple sort sequence can be 
 created per class.

Sorting using Comparator

Let have look to sort Employee list using implementation of Comparator interface. If you want to sort object other than their natural ordering at that time we use Comparator. The compare method compares its two arguments, returning a negative integer, 0, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second. Refer the below signature

public interface Comparator {
    int compare(T o1, T o2);
}

Refer below code to demonstrate the collection custom object sorting example using Comparator interface.

package com.net.technicalkeeda;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class EmployeeSort {

 /**
  * @param args
  */
 public static void main(String[] args) {
  List employees = new ArrayList();
  employees.add(new Employee(10, "Dinesh", 18000));
  employees.add(new Employee(16, "Pankaj", 19000));
  employees.add(new Employee(13, "Mayur", 14000));
  employees.add(new Employee(9, "Pravin", 22000));

  System.out.println("----Sort By Employee Id----");
  Collections.sort(employees, new EmployeeSortById());
  printEmployees(employees);
  System.out.println("----Sort By Employee Name----");
  Collections.sort(employees, new EmployeeSortByName());
  printEmployees(employees);

 }
 
 // print employee 
 public static void printEmployees(List employees) {
  for (Employee e : employees) {
   System.out.println("Id->" + e.emplId + " Name-> " + e.empName
     + " Salary-> " + e.empSalary);
  }
 }

}

// Employee Object
class Employee {
 public int emplId;
 public String empName;
 public double empSalary;

 public Employee(int emplId, String empName, double empSalary) {
  this.emplId = emplId;
  this.empName = empName;
  this.empSalary = empSalary;
 }

}
// sort by employee id
class EmployeeSortById implements Comparator {
 public int compare(Employee emp1, Employee emp2) {
  int value = 0;
  if (emp1.emplId > emp2.emplId)
   value = 1;
  else if (emp1.emplId < emp2.emplId)
   value = -1;
  else if (emp1.emplId == emp2.emplId)
   value = 0;

  return value;
 }
}
// sort by name
class EmployeeSortByName implements Comparator {
 public int compare(Employee emp1, Employee emp2) {
  return emp1.empName.compareTo(emp2.empName);
 }
}

Output of EmployeeSort.java

----Sort By Employee Id----
Id->9 Name-> Pravin Salary-> 22000.0
Id->10 Name-> Dinesh Salary-> 18000.0
Id->13 Name-> Mayur Salary-> 14000.0
Id->16 Name-> Pankaj Salary-> 19000.0
----Sort By Employee Name----
Id->10 Name-> Dinesh Salary-> 18000.0
Id->13 Name-> Mayur Salary-> 14000.0
Id->16 Name-> Pankaj Salary-> 19000.0
Id->9 Name-> Pravin Salary-> 22000.0

Java Comparable Example

package com.net.technicalkeeda;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmployeeComparableSort {

 /**
  * @param args
  */
 public static void main(String[] args) {
  List employees = new ArrayList();
  employees.add(new Employee(10, "Dinesh", 18000));
  employees.add(new Employee(16, "Pankaj", 19000));
  employees.add(new Employee(13, "Mayur", 14000));
  employees.add(new Employee(9, "Pravin", 22000));

  System.out.println("----Sort By Employee Id----");
  Collections.sort(employees);
  printEmployees(employees);

 }

 // print employee
 public static void printEmployees(List employees) {
  for (Employee e : employees) {
   System.out.println("Id->" + e.emplId + " Name-> " + e.empName
     + " Salary-> " + e.empSalary);
  }
 }

}

// Employee Object
class Employee implements Comparable {
 public int emplId;
 public String empName;
 public double empSalary;

 public Employee(int emplId, String empName, double empSalary) {
  this.emplId = emplId;
  this.empName = empName;
  this.empSalary = empSalary;
 }

 public int compareTo(Employee otherEmployee) {
  int id = ((Employee) otherEmployee).emplId; // same type object
  if (this.emplId > id)
   return 1;
  else if (this.emplId < id)
   return -1;
  else
   return 0;
 }

}

Output of EmployeeComparableSort.java

----Sort By Employee Id----
Id->9 Name-> Pravin Salary-> 22000.0
Id->10 Name-> Dinesh Salary-> 18000.0
Id->13 Name-> Mayur Salary-> 14000.0
Id->16 Name-> Pankaj Salary-> 19000.0

Tags Java  Java Sorting 


HTML Comment Box is loading comments...

Hi I am Yashwant Chavan founder of www.technicalkeeda.com, Purpose of this website to share the programming knowledge in the form post , blogs and articles.

Latest Updates

Stay updated with latest post, articles and technical discussions.

Most Popular Articles



© technicalkeeda.com 2014