Java Comparator Interface – Working of Collections.Sort()

Stay updated with the latest technology trends while you're on the move - Join DataFlair's Telegram Channel

1. Objective

In our last tutorial, we discuss Interface in Java. Here, in this Java Comparator tutorial, we are going to learn about the comparator interface in Java programming, it is an example of Java library, used to sort a collection with Java comparator example and working of Collections.Sort().

So, let’s start Java Comparator Tutorial.

Java Comparator Interface-Comparator Interface in Java

Java Comparator Interface – Working of Collections.Sort()

2. Java Comparator Interface

Comparator interface in Java is utilized to arrange the objects of user characterized classes. Java comparator operator is perfect for looking at two objects of two distinct Java classes.

Following function is used to compare the objects obj1 and obj2.

Syntax –

public int compare(Object obj1, Object obj2):

Read more about Java Class – Java Inner Class & Java Character Class 

Example –

Assume we have Java array/array list of our own class write, containing fields like roll no., name, address, DOB and so on and we have to sort the cluster in view of Roll no or name?

Method 1 –

One evident approach is to compose our own sort() work utilizing one of the standard calculations. This arrangement requires revising the entire sorting code for various basis like Roll No. what’s more, Name.

Method 2 –

Utilizing comparator interface- Java Comparator interface is utilized to arrange the objects of a user-defined class. This interface in Java is available java.util bundle and contains 2 strategies compare (Object obj1, Object obj2) and equals (Object component).

Utilizing a comparator, we can sort the components in view of information individuals. For example, it might be on roll no, name, age or whatever else.

Let’s learn How Java Inheritance is used in detail

3. Working of Collections.Sort()

Inside the Sort technique calls Compare strategy for the classes it is arranging. To look at two components, it asks “Which is more prominent?” Compare technique returns – 1, 0 or 1 to state on the off chance that it is not as much as, equivalent, or more noteworthy to the next. It utilizes this outcome to then decide whether they ought to swap for its sort.

Example- 

importjava.util.*;
importjava.lang.*;
importjava.io.*;
// A class to represent a student.
class Student
   {
       int rollno;
       String name, address;
// Constructor
       public Student(int rollno, String name, String address)
             {
                 this.rollno = rollno;
                 this.name = name;
                 this.address = address;
             }
// Used to print student details in main()
      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);
              }
     }
// Driver class
class Main
   {
       public static void main (String[] args)
           {
                ArrayList<Student> ar = new ArrayList<Student>();
                ar.add(new Student(111, "bbbb", "london"));
                ar.add(new Student(131, "aaaa", "nyc"));
                ar.add(new Student(121, "cccc", "jaipur"));
                System.out.println("Unsorted");
                for (int i=0; i<ar.size(); i++)
                System.out.println(ar.get(i));
                Collections.sort(ar, new Sortbyroll());
                System.out.println("\nSorted by rollno");
                for (int i=0; i<ar.size(); i++)
                System.out.println(ar.get(i));
                Collections.sort(ar, new Sortbyname());
                System.out.println("\nSorted by name");
                for (int i=0; i<ar.size(); i++)
                System.out.println(ar.get(i));
        }       
   }

Read about Method Overriding in Java 

So, this was all about Java Comparator interface. Hope you like our explanation.

Java Quiz

4. Conclusion

In this Java Comparator tutorial, we studied Comparator Interface in Java with its example and Working of Collections.Sort(). Which we use while using the interface in Java. Furthermore, if you have any query, feel free to ask in the comment section.

See Also- How to Install Java in Windows & Linux

For reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.