Last Updated 13. January 2021 as of

Comparator in Java is an interface whose task is to compare the objects of a user class if the class does not implement the Comparable interface.

In other words, Java Comparator is used when :

  • The objects to be ordered do not have the natural order defined by the Comparable interface.
  • You want to get rid of elements that deviate from their natural order.

In either case, you can specify a Comparator object when building a set or a map.

The comparison interface was introduced in Java version 1.2. It is included in the java.util.comparator package.

Comparator in Java | Use, Example

Explanation of the comparison interface

A comparator is a generic interface that can be declared generic, like this :

Here the parameter T represents the type of objects (or elements) to be compared.

Java Interface Comparison Method

The comparison interface provides the following two methods:

1. int comparison (Object obj1, Object obj2) : It compares the first object obj1 with the second object obj2. Returns zero if the objects are equal (i.e. obj1 == obj2).

It returns a positive value if obj1 is greater than obj2 (i.e. obj1 > obj2). Otherwise, a negative value is returned.

Let’s take an example to understand it better. The comparator looks like this:

public interface Comparator
{
int comparison (country a, country b);
}

The call to com.compare(a, b); returns a negative value if a comes before b, 0 if a and b are equal, and a positive value. Here com is an object of a class that implements Comparator.

The compare() method can throw an exception called ClassCastException if the types of objects to be compared are not compatible.

By replacing the comparison method ( ), we can change the order of the objects. All the way to the z. B. Sort the items in reverse order, you can create a Comparator object that reverses the result of the comparison.

2. equal boolean (object-object) : The equals() method defined in the comparison interface is replaced by the equals() method of the Object class. It checks if an object is equal to the call comparator.

Here the parameter object is the object whose equality is checked. If the object and the calling object are comparison objects and use the same order, then the equals() method returns true. Otherwise you get a false return.

It is not always necessary to redefine equality ( ). If not, there is no need to override the object’s execution.

The full statement of the comparison class, defined in the java.util package, is as follows

public interface compare {
// An abstract method declared in the interface
int compare(Object obj1, Object obj2);
// Declares again the equals() method of the object class
boolean equal to (Object obj);
}

Examples of comparison-based sorting programs in Java

As an example, let’s take a program in which we execute some sort of integer elements in ascending order using the comparator. Review the following source code to understand the power of the custom comparator.

Program source code 1 :

Import java.util.comparator;
// To sort items in ascending order.
public class Ascend implements the comparator
{
@Override
public int compare (Integer i1, Integer i2) {
returns i1.compareTo(i2);
}
// There is no need to replace the method, it is equivalent.
}
import java.util.TreeSet ;
public class CompTest {
public static void main(String[] args)
{
// Create an Ascend class object.
Ascension as = new Ascension() ;

// Create a set of trees and pass the reference variable of the class Ascend as a parameter.
TreeSet ts = new TreeSet(as) ;

// Adds elements to the tree.
ts.add(25);
ts.add(15);
ts.add(30);
ts.add(10);
ts.add(40);
ts.add(05) ;

// Show items in ascending order.
System.out.println(sorted in ascending order);
for (Integer element: ts)
System.out.print(element +);
System.out.println();
}
}

Go away:
Ranking in ascending order
5 10 15 25 30 40

Explanation: Look closely at the Ascend class, which implements the Comparator method and replaces the compare( ) method. As explained above, the equal( ) bypass method is needed here. In the compare( ) method, the compareTo( ) function compares two integers.

To sort items in descending order using the Javacomparator.

Let’s write a program to sort items in descending order using the Comparator in Java. Look at the source code.

Program source code 2 :

import java.util.comparator;
// To sort items in descending order. The public class
Descend implements Comparator{
@Override // Implements the compare() method for inverse integer comparison.
public int compare(Integer i1, Integer i2)
{
// For inverse comparison.
return i2.compareTo(i1);
}
}
import java.util.TreeSet;
public class CompTest {
public static void main(String[] args)
{
// Create a class object Values.
Decline ds = new Decline() ;

// Create a set of trees and pass the reference variable of the Descends class as a parameter.
TreeSet ts = new TreeSet(ds) ;

// Adds elements to the entire tree.
ts.add(25);
ts.add(15);
ts.add(30);
ts.add(10);
ts.add(40);
ts.add(05) ;

// Show items in ascending order.
System.out.println(sorted in descending order);
for (Integer element: ts)
System.out.print(element +);
System.out.println();
}
}

Go away:
Ranked in descending order
40 30 25 15 10 5

Let’s take another example of a program similar to the one above, where we perform an inverse string equation.

Program source code 3 :

import java.util.comparator;
// To sort items in descending order.
public class RevStrComp implements Comparator{
@Override // Elements of the compare() method for comparing inverse strings.
public int compare(String str1, String str2)
{
// For an inverse comparison.
return str2.compareTo(str1);
}
}
import java.util.TreeSet;
public class CompTest {
public static void main(String[] args)
{
// Creation of the object class RevStrComp.
RevStrComp rsc = new RevStrComp() ;

// Create a set of trees and pass the reference variable of the RevStrComp class as a parameter.
TreeSet ts = new TreeSet(rsc) ;

// Adds elements to the whole tree.
ts.add(cat);
ts.add(elephant);
ts.add(lion);
ts.add(dog);
ts.add(tiger);
ts.add(horse) ;

// Show items in ascending order.
System.out.println(Sort in reverse order);
for (String element: ts)
System.out.print(element +);
System.out.println();
}
}

Go away:
Sorted in reverse order
Tiger Lion Horse Elephant Cat

Sorting field with comparator

Let’s take an example of a program where we sort an array with a group of integer elements (objects) using Comparator in Java.

Here we take the table elements from the keyboard and sort them in ascending and descending order. Take a look at the following source code.

Program source code 4 :

Import java.util.comparator;
// To sort items in ascending order.
Public class Ascend implements Comparator
{
@Override
public int comparison(Integer i1, Integer i2) {
returns i1.compareTo(i2);
}
}
imports java.util.comparator;
// To sort the elements in descending order.
public class Descends implements Comparator{
@Override
public int compare (Integer i1, Integer i2)
{
// For an inverse comparison.
returns i2.compareTo(i1);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays ;
public class ArraysCompTest [
public static void main(String[] args) throws NumberFormatException, IOException
[
// Create an object of the InputStreamReader class to receive array elements from the keyboard.
InputStreamReader isr = new InputStreamReader(System.in) ;

// Create a BufferedReader object and pass the reference variable to the constructor.
BufferedReader br = new BufferedReader(isr) ;

System.out.println(How many elements do you want to enter?);
int size = Integer.parseInt(br.readLine()) ;

// Create an array to store elements or objects of the entire type.
Integer arr[] = new integer [size] ;

// Now convert the int values into integer objects and then pass them into an array to store them.
for(int i = 0 ; i < size ; i++){
System.out.println(Enter your number :);
arr[i] = Integer.parseInt(br.readLine());
}
// Create an object of the Ascend class.
Ascend if = new Ascend() method;
// Call the sort() method to sort the elements of the array in ascending order.
Arrays.sort(arr, as); // to sort in ascending order.
// Displays the sorted items in the table.
System.out.println(nSorts in ascending order: );
display(arr) ;

// Create an object of type Descend.
Descent ds = new Descent();
// Call the sort() method to sort the elements of the array in descending order.
Arrays.sort(arr, ds); // to sort in descending order.
// Displays the sorted items in the table.
System.out.println(nSorts in descending order: );
display(arr);
}
static display void(Integer arr[]){
for(Integer element: arr){
System.out.println(element + t);
}
}
}

Go away:
How many items do you want to register?
5
Enter your number :
12
Enter your number :
10
Enter your number :
15
Enter your number :
20
Enter your number :
05

Arranged in ascending order:
5
10
12
15
20

Arranged in descending order:
20
15
12
10
5

Using equation interfaces in Java

The Comparable and Comparator interfaces are used to sort a collection or a set of items (objects). However, there are the following differences in use. They are as follows:

Using a similar interface in Java

1. A similar interface is used for natural object sorting. If we are. B. you want to sort the employee class by employeeId, this is a natural type.

2. Similar is used to create a collection of elements based on a single element (or logic), such as a name.

3. A comparison interface is used when we want to compare ourselves to another object.

Using the comparison interface in Java

1. The Comparator interface is used when we want to run a custom sort on a collection of objects. This allows for precise control of the work. If we are. For example, if you want to sort an employee class by name and age, this is a custom sort.

2. The comparator is used to sort a collection of elements by, for example, multiple elements (or logic). B. by name, age, class, etc.

3. The comparison interface is used when we want to compare two different objects.

We hope this tutorial has covered important points regarding the comparison interface in Java with example programs. I hope you have understood and learned the model programs in practice.
Thanks for reading!

 comparable in javajava comparator lambdacollection algorithms in javaarrays.sort comparatorjava comparator stack overflowcompare() method in javajava comparator comparingcomparator to comparabled fb w comparable and comparatorhow to test comparator javahow to compare two custom objects in javacomparator in java 8what does the hashcode() method?java 12 comparablecomparable and comparator in java edurekahow comparable affects the original classjava comparator example sortcollections beginners bookcollection interview questionshow to make a java class comparableiterator in java howtodoinjavaexample implements comparablenatural ordering of elements javanatural ordering javalist iterator methods in javajava sort comparator lambdasort comparator c++java collections sort comparatorarrays.sort with comparatorcomparator.comparing javajava sort arraylist of objects by fieldhow to create comparator object javajava make class sortablecollections sort comparator lambdasorting custom objects in javacomparator.comparing reverselibrary comparable javawhen to use comparable and comparator in java with examplecomparator and comparable in javacomparable example in javacomparable example in java 8java string comparator

You May Also Like

🥇 Upload Videos on Twitch  Step by Step Guide ▷ 2020

Le contenu en ligne est de plus en plus populaire auprès des…

How to Use AirPlay on Mac [Two Different Ways]

Airplay lets you stream videos, music, photos, and more to your Mac,…

Prevent Automatic Codec Download on Windows Media Player

Windows Media Player automatically loads codecs (short for decoder codecs or compressor…

What To Do When Windows 10 Computer Won’t Shut Down

The computer shutdown process is started when the user does not need…