Saturday, January 11, 2020

Sorting in Collections(Comparable and Comparator Interfaces)

Sorting Lists in Collections

Comparable and Comparator Interfaces

Sorting Lists in java (Collections Framework)

Sorting can be applied in two ways
  • By implementing the Comparable interface
  • By implementing the Comparator interface

Sorting the elements in Java Collections is a very important problem. Sorting a collection composed of basic types like Numbers and String is comparatively easy, but if the type is complex, like Student, Employee, Document, etc, then we need to apply some customized sorting operation because we need to provide the details upon which the sorting must be applied. For example the student class list, first we need to tell the program that upon which field(roll number, name, marks...)  the sorting must be performed.

Difference between sorting applied by the Comparable interface and the Comparator interface

Sorting the Linked List with Comparable Interface

import java.util.Collections;
import java.util.LinkedList;

class Employee implements Comparable<Employee>
      int emp_id;
      String name;
      String dept;

      Employee(int emp_id,String name,String dept)

      public int compareTo(Employee o) {
            return this.emp_id-o.emp_id;


public class Demo {

      public static void main(String[] args) {//ArrayList
            //Sorting a LinkedList
 LinkedList<Employee> emplinks=new LinkedList<>();/*Generics are the Type parameter*/
            Employee e1=new Employee(121, "John", "Sales");
            Employee e2=new Employee(23, "Alex", "Marketing");
            Employee e3=new Employee(37, "Steve", "R&D");
            Employee e4=new Employee(28, "Davis", "Sales");
            Employee e5=new Employee(73, "Peter", "HR");
            emplinks.add(e1);// Add
            for(Employee e:emplinks)

Implementing the Comparator interface to sort a TreeSet

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

class Contact implements Comparable<Contact>{
int id;
String fname;
String lname;
long mob;
public Contact(int id, String fname, String lname, long mob) {
      super(); = id;
      this.fname = fname;
      this.lname = lname;
      this.mob = mob;


public int compareTo(Contact arg0) {


public class Test {
      public static void main(String[] args) {
            //Generics are type parameters which are provided between < >
            //JVM can now identify the type of collection
            Set<Contact> tset=new TreeSet<Contact>();
            tset.add(new Contact(12, "Amit", "Sharma", 919782145));
            tset.add(new Contact(121, "Vinod", "Kumar", 919782145));
            tset.add(new Contact(74, "Anil", "Gupta", 919782145));
            tset.add(new Contact(98, "Sourav", "Puri", 919782145));
            tset.add(new Contact(100, "Vinay", "Verma", 919782145));
            Iterator<Contact> i=tset.iterator();

Video Tutorial