Sorting Collections in Java

Sorting Collections in Java with Examples

In this article, I am going to discuss Sorting Collections in Java with Examples. Please read our previous article where we discussed Map Collections in Java with Examples. As part of this article, we are going to discuss the following pointers in detail.

  1. Sorting Collections in Java
  2. Methods of Collections class for sorting List elements
  3. Comparable Interface in Java
  4. compareTo() Method
  5. Sorting primitive type collections in Java
  6. Sorting User-Defined Class Collection in Java
  7. Comparator Interface in Java
  8. Methods of Comparator
  9. Difference Between Comparable and Comparator in Java
Sorting Collections in Java:

Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

Methods of Collections class for sorting List elements

public void sort(List list): It is used to sort the elements of List. List elements must be of the Comparable type. We can sort the elements of:

  1. String objects
  2. Wrapper class objects
  3. User-defined class objects

To perform the sorting operation on collection elements, we have two interfaces:

  1. Comparable Interface
  2. Comparator Interface
Comparable Interface in Java

Comparable Interface belongs to java.lang package. The Comparable interface contains a method compareTo() and this method contains some sorting logic for comparing one element with another. It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data members only. For example, it may be rollno, name, age, or anything else.

compareTo() Method

The compareTo() Method internally called by the collection algorithm (mostly implemented on Bubble sort Techniques). Whenever if this element is less than the passed element it returns a negative value. If both elements are equal it returns zero. If this element is greater than the passed element then it returns a positive value.

Note: In Java, some of the below classes by default implements the comparable interface, i.e., String, Integer, Float, Double, etc.

Collection Framework provides one of the class, i.e. Collections which contains some of the static methods, i.e., sort(), reverse(), shuffle(). The above static methods contain a built-in collection algorithm or sorting algorithm to perform the operation on only list interface collections i.e., arraylist, linkedlist, vector.

Syntax of sort() : Collection.sort(list object);

Sample Program to sort primitive type collections in Java
import java.util.Collections;
import java.util.Vector;
import java.util.*;
public class SortingDemo1
{
    static void display (Vector < Integer > ob)
    {
        for (Integer i1:ob)
        {
         System.out.println (i1);
        }
    }
    public static void main (String[]args)
    {
        Vector < Integer > v1 = new Vector < Integer > ();
        v1.add (40);
        v1.add (10);
        v1.add (20);
        v1.add (30);
        System.out.println ("General order");
        display (v1);
        System.out.println ("Ascending order");
        Collections.sort (v1);
        display (v1);
        System.out.println ("Descending order");
        Collections.reverse (v1);
        display (v1);
        System.out.println ("Shuffling order");
        Collections.shuffle (v1);
        display (v1);
    }
}

Output:

sort primitive type collections in Java

In the above application, the static method reverse is responsible to reverse the current order of collection.

Note: If the current order is ascending then it becomes a descending order.

In the above application, sort() method calls compareTo() method of given generic type i.e., integer class and this method contains a built-in sorting logic i.e., comparing this element with parsed element i.e., Ascending Order.

Sorting User-Defined Class Collection in Java:

To perform sorting operations on user-defined class objects added in the collection we need to follow below steps:

  1. Define a Java class that must implement java.lang.comparable<E>
  2. Override compareTo() and provide a user-defined sorting logic.

Note: User-Defined sorting logic is required whenever to sort Employee objects based on Employee number or name, etc.

Sample Program to sort user-defined collection in Java:
import java.util.*;
class Employee implements Comparable < Employee >
{
    int empno;
    String ename;
    Employee (int i, String j)
    {
        empno = i;
        ename = j;
    }
    public int compareTo (Employee e1)
    {
        Integer i1 = this.empno;
        Integer i2 = e1.empno;
        return i1.compareTo (i2);
    }
    static void display (Vector < Employee > ob)
    {
        for (Employee e1:ob)
        {
         System.out.println (e1.empno + "," + e1.ename);
        }
    }
}

public class SortingDemo2
{
    public static void main (String[]args)
    {
        Vector < Employee > v1 = new Vector < Employee > ();
        v1.add (new Employee (1001, "a"));
        v1.add (new Employee (1004, "d"));
        v1.add (new Employee (1003, "c"));
        v1.add (new Employee (1002, "b"));
        System.out.println ("General format.....");
        Employee.display (v1);
        System.out.println ("After Sorting.....");
        Collections.sort (v1);
        Employee.display (v1);
    }
}

Output:

Sample Program to sorting user defined collections in Java

Sample Program to sort a collection of string type in Java
import java.util.*;
public class SortingDemo3
{
    static void display (ArrayList < String > ob)
    {
        for (String i:ob)
            System.out.println (i);
    }
    public static void main (String[]args)
    {
        ArrayList < String > ob = new ArrayList < String > ();
        ob.add ("India");
        ob.add ("USA");
        ob.add ("Denmark");
        display (ob);
        Collections.sort (ob);
        System.out.println ("\nAscending Order...");
        display (ob);
    }
}

Output:

Sample Program to sort a collection of string type in Java

In the above application sort() invokes compareTo() on the given generic type i.e., in this case, String type. Internally string class compareTo() is responsible to compare this element and passed element ASCII Code and depends on the ASCII Code value it decides which type of String element is greatest.

Note: This compareTo() Method internally uses “Ascending Logic” i.e., comparing this element with parsed element.

Test Logic:
public int compareTo(Employee e1)
{
 String i1 = this.ename;
        String i2 = e1.ename;
        return i1.compareTo(i2);   //Ascending
        //return i2.compareTo(i1);  //Descending
}
static void display(Vector<Employee> ob)
{
 for(Employee e1:ob)
 {
  System.out.println(e1.ename +”,”);
  System.out.println(e1.ename);
 }
}

The drawback of Comparable Interface: It makes application as sorting logic dependent.

Comparator Interface in Java

Java Comparator interface is used to order the objects of a user-defined class. This interface is found in java.util package. To make application as sorting logic dependent we need to use a “Comparator Interface”.

Using Comparator Interface we can separate sorting logic from the business logic of the application. It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age, or anything else.

Steps to work with a Comparator:
  1. Define the Java class and that must implement a Comparator Interface.
  2. Override compare method and in that provide a sorting logic.
Methods of Comparator
  1. public int compare(Object obj1, Object obj2): It compares the first object with the second object.
  2. public boolean equals(Object obj): It is used to compare the current object with the specified object.
Sample Program to understand Comparator to sort a collection in java
import java.util.*;
class Employee
{
    int empno;
    String ename;
    Employee (int i, String j)
    {
        empno = i;
        ename = j;
    }
}
class EmpnameWise implements Comparator < Employee >
{
    public int compare (Employee e1, Employee e2)
    {
        String i = e1.ename;
        String j = e2.ename;
        return i.compareTo (j);
    }
}

class EmpnoWise implements Comparator < Employee >
{
    public int compare (Employee e1, Employee e2)
    {
        Integer i1 = e1.empno;
        Integer i2 = e2.empno;
        return i1.compareTo (i2);
    }
}

public class TestComparator 
{
    static void display (ArrayList < Employee > ob)
    {
        for (Employee e1:ob)
        {
         System.out.println (e1.empno + "," + e1.ename);
        }
    }

    public static void main (String[]args)
    {
        ArrayList < Employee > a1 = new ArrayList < Employee > ();
        a1.add (new Employee (1, "d"));
        a1.add (new Employee (2, "a"));
        a1.add (new Employee (3, "c"));
        a1.add (new Employee (4, "b"));
        int i = 0;
        if (args.length == 1)
        {
         i = Integer.parseInt (args[0]);
        }
        
        if (i == 1)
        {
         EmpnoWise ob = new EmpnoWise ();
         Collections.sort (a1, ob);
         display (a1);
        }
        else
        {
         EmpnameWise ob = new EmpnameWise ();
         Collections.sort (a1, ob);
         display (a1);
        }
    }
}

Output:

Program to understand Comparator to sort a collection in java

In the above application sort() of Collections, the class uses the given custom comparator object and it invokes compare() method on the given object to perform sorting operations on the given collections.

Difference Between Comparable and Comparator in Java

Comparable:

  1. This interface belongs to java.lang package.
  2. This interface contains compareTo() method used for sorting purposes.
  3. This interface makes application as sorting logic dependent.

Comparator:

  1. This interface belongs to java.util package.
  2. This interface contains a compare() method used for sorting purposes.
  3. This interface makes application as sorting logic independently.

In the next article, I am going to discuss Generics in Java with examples. Here, in this article, I try to explain Sorting Collections in Java with Examples and I hope you enjoy this Sorting Collections in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *