AppDividend
Latest Code Tutorials

Java Comparator Interface Tutorial | Comparator Interface in Java Example

0

Java Comparator Interface Tutorial | Comparator Interface in Java Example is today’s topic. Java Comparator interface is used to sort an array or list of objects based on a custom order. Custom ordering of elements is imposed by implementing Comparator.compare() method in the objects.

Java Comparator interface does total ordering of the objects which may not have a natural ordering. For example, for a list of student object, the natural order may be ordered by student id. But in real life applications, we may want to sort the list of a student by their first name, date of birth or simply any other such criteria. In such conditions, we need to use the Comparator interface.

Java Comparator Interface Tutorial

Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes.

Use of java comparator

Sort the array or list of objects where we can not modify the object’s source code to implement Comparable interface. Java Comparator provides multiple sorting sequences, i.e., elements can be sorted or classified on the basis of any number which are roll number, age, id number, etc.

Methods of Java Comparator Interface

Method Description
public int compare(Object obj1, Object obj2) It compares the first object with the second object.
public boolean equals(Object obj) It is used to compare the current object with the specified object.
public boolean equals(Object obj) It is used to compare the current object with the specified object.

Comparator.compare()

To empower all out requesting on articles, we have to make a class which actualizes the Comparator interface. At that point, we have to supersede its compare(T o1, T o2) strategy.

It looks at its two contentions for request. It restores a negative number, zero, or a positive whole number as the principal contention is not exactly, equivalent to, or more noteworthy than the second.

The practitioner should likewise guarantee that the connection is transitive: ((compare(x, y)>0) &&
(compare(y, z) > 0)) suggests compare(x, z) > 0.

See the following code example.

// Student.java

import java.util.*;

class Student {

    int rollno;
    String name, address;
  
    public Student(int rollno, String name, String address) {
      this.rollno = rollno;
      this.name = name;
      this.address = address;
    }
    
    // Getters and Setters
    @Override
    public String toString() {
        return this.rollno + " " + this.name + " " + this.address;
    }
}

class Sortbyroll implements Comparator<Student> {
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student a, Student b) {
        return a.rollno - b.rollno;
    }
}

class Sortbyname implements Comparator<Student> {
    // Used for sorting in ascending order of
    // roll name
    public int compare(Student a, Student b) {
        return a.name.compareTo(b.name);
    }
}

class Main {
    public static void main(String[] args) {
        ArrayList<Student> al = new ArrayList<Student>();
        al.add(new Student(18, "KB", "london"));
        al.add(new Student(19, "SM", "nyc"));
        al.add(new Student(21, "KL", "jaipur"));

        System.out.println("Unsorted");
        for (int i = 0; i < al.size(); i++)
            System.out.println(al.get(i));

        Collections.sort(al, new Sortbyroll());

        System.out.println("\nSorted by rollno");
        for (int i = 0; i < al.size(); i++)
            System.out.println(al.get(i));

        Collections.sort(al, new Sortbyname());

        System.out.println("\nSorted by name");
        for (int i = 0; i < al.size(); i++)
            System.out.println(al.get(i));
    }
}

See the below output.

Java Comparator Interface Tutorial

 

Collections.sort() and Arrays.sort()

  1. Use Collections.sort(list, Comparator) method sort a list of objects in order imposed by provided comparator instance.
  2. Use Arrays.sort(array, Comparator) method sort an array of objects in the order imposed by provided comparator instance.

Finally, Java Comparator Interface Tutorial | Comparator Interface in Java Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.