What Is a Comparator in Java?

This site contains affiliate links to products. We may receive a commission for purchases made through these links.

A comparator in Java can be a challenging topic to wrap your head around, especially if you’re starting your Java journey. However, once you understand what it is, its implementation, and its use, you shouldn’t face any challenges.

In this write-up, we will discuss what is a comparator in Java, how it is used and how it is triggered. We will also differentiate a comparator from a comparable because the two are often interchanged for one another. So, keep reading to find out more.

What Is a Comparator in Java?

If you’ve been searching for “what is a comparator in Java,” you’ve probably encountered jargon that was hard to understand. Fortunately, it is a relatively easy concept to understand.

A comparator in Java is an interface used to compare or sort two objects that don’t belong to the same user-defined class. The Java comparator interface is part of the java.util package and belongs to the Java collections framework. It is mainly used for ordering objects of an array or collection.

A comparator contains two main methods: compare () and equals (). However, compare () is the most commonly used of the two methods.

A comparator can pass a sorting algorithm as a function parameter to the Arrays.sort() or Collection.sort() methods. You can create different implementations of the comparator interface to sort an array or a collection of objects based on any particular field. In other words, you can create multiple performances of comparators for a single user-defined class.

For example, suppose you have s “student” class with two fields, studentId and studentName. In that case, you can create a separate comparator interface to sort the students according to their IDs and another different comparator Interface to sort students according to their names. Whenever you want to sort the students according to IDs, you can start the ID comparator; whenever you want to sort them according to their names, you can begin the name comparator.

Syntax of a Comparator

public int compare(Object obj1, Object obj2):

Please note that obj1 and obj2 stand for the comparison of the two objects.

How to Implement a Comparator in Java

You can implement a Comparator in Java using two major steps:

Step 1: Create a User-Defined Class That Implements Comparator <Type>

Consider the following line of code:

public class StudentIdComparator implements Comparator<Student>

The above line of code means that we are creating a comparator for the student class, and the comparator’s name is StudentIDComparator.

Step 2: Implement the Compare() Method

The compare method takes in the objects that are supposed to be compared as arguments and returns a zero, negative or positive value. Here’s how you implement the Compare() method based on the comparator syntax shown in Step 1 above:

@override

public int compare( Student student1, Student student 2){

return student1.getStudentId() – student2.getStudentId()

}

In the above code, the compare () method compares two objects: student1 and student2. The return statement, on the other hand, contains the logic of our comparison. As you can see, we are comparing the IDs of student 1 and student 2. Whichever ID is less will be ranked in the lower order.

The return statement can return zero, negative or positive values as the output. Here are the semantics of what the result means:

  • A negative output signals that the first argument in the compare () method is less than the second argument.
  • An output of 0 signals that the two arguments passed in the compare () method are equal.
  • A positive output signals that the first argument passed in the compare () method is greater than the second.

To implement the Java comparator interface, one must adhere to the following transitive comparison rule:

If X is greater than Y, and Y is greater than Z, then X must also be greater than Z.

How to Start the Sorting for Collection and Array Items

As of now, we have just seen how to implement comparators in Java. However, you have to call the above code for the actual comparison to occur. To sort the items of objects in a collection, we use the following syntax:

Collections.sort( <list>, new <Comparator class implementation>);

Let us look at an example:

Collections.sort(student, new StudentIdComparator() );

When the above line of code is executed, students will be sorted according to their IDs because we call on the StudentIdComparator() method.

We can similarly sort objects in an array using the Array.sort() method. For example:

Student[] StudentArray = {student1, student2, student3, student4, student5}

Array.sort( StudentArray, new StudentIdComparator() )

What Is a Comparator in Java

Source Code Example

Now let us look at the practical examples of implementing a comparator in your code. First, create a class called “Student.” Now, write the following code in the file name below:

Student.java

package com.javaComparator;

public class Student{

int studentId;

String studentName;

public Student( int studentId, String studentName){

this.studentId = studentId;

this.studentName = studentName;

}

public int getStudentId() {

return studentId;

}

public void setStudentId(int studentId){

this.studentMarks = studentId;

}

public String getStudentName(){

return studentName;

}

public void setStudentName(String studentName){

this.StudentName = studentName;

}

public String toString(){

return studentId + “ : “ + studentName;

}

}

The above code initiates a class called “Student” and triggers the getters and setters for the student ID and name. The return statement concatenates the ID of the student along with the name.

Now that we have the Student class ready, go ahead and create a class named “StudentIdComparator.” In this file, we will implement a comparator called studentIDComparator. This comparator will be used to compare the student’s name and the ID when triggered. In the StudentIdComparator.java file, write the code below:

StudentIdComparator.java

package com.javaComparator;

import java.util.Comparator;

public class StudentIdComparator implements Comparator<Student>{

@override

public int compare( Student student1, Student student2){

return student1.getStudentId() – student2.getStudentId();

}

}

The last step calls on the comparator you have just created above. Please note that this step depends on whether you’re sorting objects of a collection or an array. If you’re ordering objects of a collection, write the code below:

ComparatorExample.java

package com.javaComparator;

import java.util.Collection;

import java.util.List

import java.util.ArrayList;

public class ComparatorExample{

public static void main(String[] args) {

List<Student> students = new ArrayList<Student> ();

Student student1 = new Student( 10, “John”);

Student student2 = new Student( 5, “Jane”);

Student student3 = new Student( 3, “James”);

Student student4 = new Student( 11, “Jack”);

Student student5 = new Student( 4, “Rachel”);

students.add(student1);

students.add(student2);

students.add(student3);

students.add(student4);

students.add(student5);

Collections.sort(students, new StudentIdComparator();

for(Student student : students){

System.out.println(student);

}

The output of the above code snippet should order the students based on ascending order of their IDs.

If you’re sorting objects of a collection, write the following code instead:

ComparatorExample.java

package com.javaComparator;

import java.util.Collection;

import java.util.List

import java.util.Array

import java.util.ArrayList;

public class ComparatorExample{

public static void main(String[] args) {

List<Student> students = new ArrayList<Student> ();

Student student1 = new Student( 10, “John”);

Student student2 = new Student( 5, “Jane”);

Student student3 = new Student( 3, “James”);

Student student4 = new Student( 11, “Jack”);

Student student5 = new Student( 4, “Rachel”);

students.add(student1);

students.add(student2);

students.add(student3);

students.add(student4);

students.add(student5);

Student[] StudentArray = {student1, student2, student3, student4, student5}

Array.sort( StudentArray, new StudentIdComparator() )

for(Student student : studentArray){

System.out.println(student);

}

The output of the above code should also print out students based on their IDs.

How to Implement a Comparator in Java Anonymously

In the above examples, we have created the StudentIdComparator comparator in a separate class, and now we can explicitly call it whenever we need to use it. This method comes in handy, especially when we need to reuse the code in different classes.

However, if you want to use a comparator in a single place, it’s best to trigger it anonymously. In this case, you don’t need to implement the comparator in a different file or class. Here is an example:

ComparatorExample.java

package com.javaComparator;

import java.util.Collection;

import java.util.Comparator

public class ComparatorExample{

public static void main(String[] args) {

List<Student> students = new ArrayList<Student> ();

Student student1 = new Student( 10, “John”);

Student student2 = new Student( 5, “Jane”);

Student student3 = new Student( 3, “James”);

Student student4 = new Student( 11, “Jack”);

Student student5 = new Student( 4, “Rachel”);

students.add(student1);

students.add(student2);

students.add(student3);

students.add(student4);

students.add(student5);

Collections.sort(students,

new Comparator <Student>(){

@override

public int compare(Student o1, Student o2){

return o1.getStudentName().compareTo(o2.getStudentName());

}

}

);

for(Student student : studentArray){

System.out.println(student);

}

The output of the above code should order students alphabetically by name.

Frequently Asked Question

What is the difference between a comparable and a comparator in Java?

This is a common question you’ll likely be asked in a Java interview. The main difference is that a comparable provides a single sorting sequence. In other words, you can only sort a collection based on a single element, such as the ID and the name.

On the other hand, a comparator provides multiple sorting sequences. For instance, we can sort a collection using various elements such as the ID and the name.

Another major difference between a comparator and a comparable is that a comparator doesn’t affect the original class, while a comparable does.

Key Takeaways on Comparator in Java

Creating a standalone class that implements the comparator interface is best if you want to use it in different places across your code. Otherwise, you can make the comparator implementation anonymously if you’re going to use the comparator in one place.

Speaking Fluent Java for Efficient Sorting

Comparators are one of the best ways of sorting objects, not within the same user-defined class. What’s more interesting is that you can call one comparator across different classes, saving you the headache of rewriting the same code multiple times.

Thus, your code will be much cleaner, and you’ll save a lot of time. However, there’s no problem with anonymizing a comparator if you’re going to use it once or use it in a single class.

So, if you were wondering, “what is a comparator in Java,” we hope that your question has been answered and you can now use comparators in your Java projects.

Leave a Comment

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

Special offer for our visitors

Get your Free Coding Handbook

We will never send you spam. By signing up for this you agree with our privacy policy and to receive regular updates via email in regards to industry news and promotions