Categories: Java

Comparator Interface in Java Collection Framework

To sort the objects of user-defined classes, a comparator interface is utilized. A comparator object can compare two items of the same type.
This interface may be found in java.util package and includes two methods:

  • compare(Object obj1,Object obj2)
  • equals (Object element).

It supports different sorting sequences, which means you can sort the items based on any data member, such as rollno, name, age, or anything else.

Syntax:
class MyComparator implements Comparator<Class-name>{}
public int compare(Object obj1, Object obj2)

The following are the rules for utilizing the Comparator interface:

  • You must implement the Comparator interface if you want to sort the elements of a collection.
  • If you do not mention the type of the object in your Comparator interface, it will presume that you are sorting objects of type Object. As a result, while overriding the compare() method, you must specify the parameter type as Object only.
  • If you want to order the user-defined type elements, you must provide the user-defined type generically while implementing the Comparator interface.
  • If you do not specify the user-defined type when implementing the interface, it will default to Object and you will be unable to compare the user-defined type components in the collection.
Example:
Student class:
class Student {
 
    // Attributes of a student
    int rollno;
    String name, address;
 
    // Constructor
    public Student(int rollno, String name, String address)
    {
 
        // This keyword refers to current instance itself
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }
 public String toString()
    {
 
        // Returning attributes of Student
        return this.rollno + " " + this.name + " "
            + this.address;
    }
}
Sortbyroll Class:

Class to sort the entries according to the specified roll numbers.

class Sortbyroll implements Comparator<Student> {
 
    // Method
    // Sorting in ascending order of roll number
    public int compare(Student a, Student b)
    {
 
        return a.rollno - b.rollno;
    }
}
 
Main class:
class Coderz {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of Student type
        ArrayList<Student> ar = new ArrayList<Student>();
 
        // Adding entries in above List
        // using add() method
        ar.add(new Student(111, "Rabecca", "London"));
        ar.add(new Student(102, "Tom", "Seoul"));
        ar.add(new Student(123, "Tiffany", "Jaipur"));
        ar.add(new Student(99, "John", "Hongkong"));
 
        // Display message on console for better readability
        System.out.println("Unsorted");
 
        // Iterating over entries to print them
        for (int i = 0; i < ar.size(); i++)
            System.out.println(ar.get(i));
 
        // Sorting student entries by roll number
        Collections.sort(ar, new Sortbyroll());
 
        // Display message on console for better readability
        System.out.println("\nSorted by rollno");
 
        // Again iterating over entries to print them
        for (int i = 0; i < ar.size(); i++)
            System.out.println(ar.get(i));
    }
}
Output:
Unsorted
111 Rabecca London
102 Tom Seoul
123 Tiffany Jaipur
99 John Hongkong

Sorted by rollno
99 John Hongkong
102 Tom Seoul
111 Rabecca London
123 Tiffany Jaipur

Note: also read about the Comparable Interface in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

10 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago