Comparator Interface in Java

This article teaches one of the Java concepts, the comparator interface in Java with simple examples for a better understanding.

Comparator Interface

The Comparator Interface comes under the folder of a collection in Java used to order the objects of the user-defined class. This interface resides in the java.util package and it contains two methods, compare(object obj1, object obj2) and equals(object elements).

In the comparator interface the sorting logic is written in a different class so that different sorting logic can be used on the basis of multiple attributes of the class.

Using the comparator interface, the class itself does not need to implement any interface, rather another class implements the comparator interface to sort the collection or array of objects using the compare() method.

Comparator's compare(obj1, obj2) compares ”obj1” object with “obj2” and returns an integer value. Returns 1 if (obj1>obj2), -1 if (obj1<obj2) and 0 if (obj1==obj2).

It provides multiple sorting sequences, in other words you can sort the elements based on any data member. For example name, roll number, age or anything else.

Method of collection class for sorting list of elements

Public void sort(List list, Comparator c):
Sorts the elements of the list given by the comparator.

Example

Here we are making five Java files and all five are for various purposes.

  • Student.java

    This file includes the name, Id and rollno and a parameterized constructor.
     
  • Id.java

    This file is developed for comparison of the student on the basis of their Id.
     
  • Name.java

    This file is also used to compare the student on the basis of name and in this case we are using the compareTo() method of the string class that internally provides the comparison.
     
  • RollNo.java

    This file is also used to compare the student on the basis of rollno.
     
  • Test.java

    This file is made to test the working of the comparator interface that sorts the object values on the basis of age and the name of the student.
Now let's have a look at the example.

Student.java


public
 class Student

{

 

    private int stId;

    private String stName;

    private int stRollNo;

 

    Student(int stId, String stName, int stRollNo)

    {

        this.stId = stId;

        this.stName = stName;

        this.stRollNo = stRollNo;

    }

 

    public int getStId()

    {

        return stId;

    }

 

    public void setStId(int stId)

    {

        this.stId = stId;

    }

 

    public String getStName()

    {

        return stName;

    }

 

    public void setStName(String stName)

    {

        this.stName = stName;

    }

    public int getStRollNo()

    {

        return stRollNo;

    }

 

    public void setStRollNo(int stRollNo)

    {

        this.stRollNo = stRollNo;

    }

}

Id.java

import java.util.Comparator;

 

public class Id implements Comparator<Student> {

 

    public int compare(Student st1, Student st2) {

 

        return (st1.getStId() < st2.getStId()) ? -1

        : (st1.getStId() > st2.getStId()) ? 1 : 0;

    }

}

Name.java

import java.util.Comparator;

 

public class Name implements Comparator<Student> {

 

    public int compare(Student st1, Student st2) {

        return (st1.getStName().compareTo(st2.getStName()));

    }

}

RollNo.java

import java.util.Comparator;

 

public class RollNo implements Comparator<Student> {

 

    public int compare(Student st1, Student st2) {

 

        return (st1.getStRollNo() < st2.getStRollNo()) ? -1

        : (st1.getStRollNo() > st2.getStRollNo()) ? 1 : 0;

    }

}

Test.java

import java.util.ArrayList;

import java.util.Collections;

 

public class Test {

    public static void main(String args[]) {

 

        Student employee1 = new Student(13"Vikas"1004);

        Student employee2 = new Student(11"Ashish"1002);

        Student employee3 = new Student(14"Prashant"1001);

        Student employee4 = new Student(12"Kailash"1003);

 

        ArrayList<Student> empList = new ArrayList<Student>();

        empList.add(employee1);

        empList.add(employee2);

        empList.add(employee3);

        empList.add(employee4);

 

        System.out.println("EmpList elemnets before sorting :");

 

        for (int i = 0; i < empList.size(); i++) {

            System.out.println("EmpId: " + empList.get(i).getStId()

            + " | EmpName: " + empList.get(i).getStName() + " | EmpRollNo: " + empList.get(i).getStRollNo());

        }

 

        Collections.sort(empList, new Id());

 

        System.out.println("EmpList elemnets after sorting by id :");

 

        for (int i = 0; i < empList.size(); i++) {

            System.out.println("EmpId: " + empList.get(i).getStId()

            + " | EmpName: " + empList.get(i).getStName() + " | EmpRollNo: " + empList.get(i).getStRollNo());

        }

 

        Collections.sort(empList, new Name());

 

        System.out.println("EmpList elemnets after sorting by name :");

 

        for (int i = 0; i < empList.size(); i++) {

            System.out.println("EmpId: " + empList.get(i).getStId()

            + " | EmpName: " + empList.get(i).getStName() + " | EmpRollNo: " + empList.get(i).getStRollNo());

        }

 

        Collections.sort(empList, new RollNo());

 

        System.out.println("EmpList elemnets after sorting by RollNO :");

 

        for (int i = 0; i < empList.size(); i++) {

            System.out.println("EmpId: " + empList.get(i).getStId()

            + " | EmpName: " + empList.get(i).getStName() + " | EmpRollNo: " + empList.get(i).getStRollNo());

        }

    }

}

Output


Up Next
    Ebook Download
    View all
    Learn
    View all