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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago