×
☰ See All Chapters

Sorting in Java

Sorting Rules

  • We can sort the elements of a collection if and only if elements are comparable. Which means class must have implemented Comparable interface, if its objects are to be sorted. Objects of different or dissimilar type are not comparable. We can sort only when the elements in the collection are of similar type.  

  • We cannot sort when the elements in the collection are of dissimilar type.  

  • The sorting algorithm uses the comparison logic present in the compareTo() method of Comparable interface or compare() method of Comparator interface. 

  • To sort the elements in List (not Map, Set, Queue) java provides two static methods which are present in Collections class. 

1) public static <T extends Comparable<? super T>> void sort(List<T> list)

We can sort the elements of a collection if and only if elements are comparable. Which means class must have implemented Comparable interface, if its objects are to be sorted.

String class and Wrapper classes implements Comparable interface. So if we store String/wrapper class elements they are comparable.

2) public static <T> void sort(List<T> list, Comparator<? super T> c)

Here elements to be sorted need not to implement Comparator. We have to pass an argument to the sort() method which should have implemented Comparator Interface.

Difference between Comparable and Comparator

Comparable

Comparator

It is an interface in java.lang package.

It is an interface present in java.util package

The Comparable Interface defines only one method.

Public int compareTo(Object obj)

This method compares this object with obj object and returns an integer. Its value has following meaning

Positive=> this object is greater than obj

zero =>this object equals to obj

negative=> this object is less than obj

The Comparator interface defines two methods: compare( ) and equals( ).

int compare(T obj1, T obj2)

This method compares obj1 and obj2 objects. And returns an integer. Its value has following meaning.

positive =>obj1 is greater than obj2

zero =>obj1 equals to obj2

negative=>obj1 is less than obj2

boolean equals(Object obj)

Here, obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary while sorting, and most simple comparators will not do so.

We can sort the elements of a collection if and only if elements are comparable. Which means class must have implemented Comparable interface, if its objects are to be sorted.

Here elements to be sorted need not to implement Comparator. We have to pass an argument to the sort() method which should have implemented Comparator Interface.

 

A comparable object can compare itself with another class.

We can implement many sort sequences.

Collections.sort(List)

Here objects will be sorted on the basis of compareTo() method.

Collections.sort(List, Comparator)

Here objects will be sorted on the basis of compare() method in Comparator.

Many built in classes like String, all wrapper classes, Date, Calendar implement it.

It is generally implemented to compare 3rd party classes or our user defined classes.

Sorting Example with Comparble Interface - Sorting elements of a List that contains Wrapper class objects

ComparableDemo.java

import java.util.*;       

class ComparableDemo {

        public static void main(String[] args) {

                LinkedList list = new LinkedList();

                list.add(new Integer(102));

                list.add(new Integer(104));

                list.add(new Integer(101));

                list.add(new Integer(105));

                list.add(new Integer(103));

                System.out.println("Values in LinkedList before sort"+list);

                // use sort() of class Collections for sorting

                Collections.sort(list);

                System.out.println("Values in LinkedList after sort"+list);

        }

}

Output:

Values in LinkedList before sort[102, 104, 101, 105, 103]

Values in LinkedList after sort[101, 102, 103, 104, 105]

Sorting Example with Comparble Interface - Sorting elements of a List that contains String objects

class ComparableDemo {

        public static void main(String[] args) {

                LinkedList list = new LinkedList();

 

                list.add("C");

                list.add("A");

                list.add("E");

                list.add("B");

                list.add("D");

                list.add("F");

                list.add("H");

                list.add("G");

 

                // while sorting LinkedList cannot contain dissimilar data or null value

                // list.add(new Integer(10));

                // list.add(null);

 

                System.out.println("Values in LinkedList before sort" + list);

 

                // use sort() of class Collections for sorting

                Collections.sort(list);

                System.out.println("Values in LinkedList after sort" + list);

        }

 

}

Output:

Values in LinkedList before sort[C, A, E, B, D, F, H, G]

Values in LinkedList after sort[A, B, C, D, E, F, G, H]

Sorting Example with Comparble Interface - Sorting elements of a List that contains user defined class objects

sorting-in-java-0
 

ComparableDemo.java

class ComparableDemo {

        public static void main(String[] args) {

                LinkedList list = new LinkedList();

                list.add(new Employee(10,"Manu M"));

                list.add(new Employee(40,"AiTemp"));

                list.add(new Employee(30, "Amogh"));

                list.add(new Employee(20, "Kumar"));

               

                System.out.println("Values in LinkedList before sort"+list);

                Collections.sort(list);

                System.out.println("Values in LinkedList after sort"+list);

        }

}

Output:

Sorting based on employeeId

Values in LinkedList before sort[10   Manu M, 40   AiTemp, 30   Amogh, 20   Kumar]

Values in LinkedList after sort[10   Manu M, 20   Kumar, 30   Amogh, 40   AiTemp]

 

Sorting based on name

Values in LinkedList before sort[10   Manu M, 40   AiTemp, 30   Amogh, 20   Kumar]

Values in LinkedList after sort[40   AiTemp, 30   Amogh, 20   Kumar, 10   Manu M]

Sorting Example with Comparator Interface

import java.util.*;

class Employee{

        int employeeId;

        String name;

        public Employee(int employeeId,String name) {

                this.employeeId=employeeId;

                this.name=name;

        }

       @Override

        public String toString() {

                return employeeId +"   "+ name ;

        }

}

 

sorting-in-java-1
 

public class ComparatorDemo {

        public static void main(String[] args) {

                LinkedList list = new LinkedList();

                list.add(new Employee(10,"Manu M"));

                list.add(new Employee(40,"AiTemp"));

                list.add(new Employee(30, "Amogh"));

                list.add(new Employee(20, "Kumar"));

                System.out.println("Values in LinkedList before sort"+list);

               

            //Sorting based on employeeId

                Collections.sort(list, new EmployeeNameComparator());

               

                // set the iterator to the beginning

                System.out.println("displaying using Iterator");

                Iterator itr = list.iterator();

                while(itr.hasNext())

                {

                        Object e = itr.next();

                        Employee emp = (Employee)e;

                        System.out.println(emp.employeeId+"  "+emp.name);

                }

                System.out.println("Sorting based on employeeId"+list);       

               

            //Sorting based on name

                Collections.sort(list, new EmployeeIdComparator());

                System.out.println("Sorting based on name"+list);       

        }

}

Output:

Values in LinkedList before sort[10   Manu M, 40   AiTemp, 30   Amogh, 20   Kumar]

displaying using Iterator

10  Manu M

20  Kumar

30  Amogh

40  AiTemp

Sorting based on employeeId[10   Manu M, 20   Kumar, 30   Amogh, 40   AiTemp]

Sorting based on name[40   AiTemp, 30   Amogh, 20   Kumar, 10   Manu M]

 

 

 

 

 

 

       

 


All Chapters
Author