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.

Arrays.sort() Example

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

Collections.sort() Example

package com.net.technicalkeeda.app;

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

public class SimpleSort {
    public static void main(String[] args) {

        List <Integer> numbers = new ArrayList <Integer>();
        numbers.add(15);
        numbers.add(18);
        numbers.add(4);
        numbers.add(3);
        numbers.add(9);
        numbers.add(12);
        numbers.add(1);

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

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

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

        Collections.reverse(numbers);
        for (Integer integer: numbers) {
            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<T> {
    int compare(T o1, T o2);
}

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

Employee.java

package com.net.technicalkeeda.app;

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;
    }

}

EmployeeSortById.java

package com.net.technicalkeeda.app;

import java.util.Comparator;

// sort by employee id
class EmployeeSortById implements Comparator < Employee > {
    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;
    }
}

EmployeeSortByName.java

package com.net.technicalkeeda.app;

import java.util.Comparator;

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

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

public class EmployeeSort {


    public static void main(String[] args) {
        List <Employee> employees = new ArrayList <Employee> ();
        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("\n----Sort By Employee Name----");
        Collections.sort(employees, new EmployeeSortByName());

        printEmployees(employees);

    }

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

}

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<Employee> employees = new ArrayList<Employee>();
  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


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2016

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0302 seconds.