What is Objects.compare() in Java?

The compare() method is a static method of the Objects class. This method takes in two objects and a Comparator that compares the input objects.

  • The method returns zero if the objects are identical.
  • If the objects are not identical, the method uses the comparator to compare them.
  • If both the objects passed point to null reference, then the method returns zero.

To use the compare() method, you must import the following module.

java.util.Objects

Syntax

The syntax of the compare() method is as follows.


public static <T> int compare(T a, T b, Comparator<? super T> c)

Parameters

The compare() method takes the following parameters.

  • T a: first object.

  • T b: second object.

  • Comparator<? super T> c: The Comparator used to compare the two objects.

Return value

The method returns zero if the arguments are identical. Otherwise, it returns the return value of the compare method of the Comparator object.

Code

Example 1

In the code below, we pass the null value as objects to the method.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
Object a = null;
Object b = null;
System.out.println(Objects.compare(a, b, null));
}
}

If we run the program, it will print zero.

0

Example 2

In the code snippet below, we pass the integer values as objects to the method and an integer comparator.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
int a = 9;
int b = 4;
System.out.println(Objects.compare(a, b, Integer::compareTo));
}
}

If we run the program above, it will print 1, as the first integer object is greater than the second one.

1

Example 3

In the code below, we pass the integer values as objects to the method and an integer comparator.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
int a = 4;
int b = 9;
System.out.println(Objects.compare(a, b, Integer::compareTo));
}
}

If we run the program above, it should print -1, as the first integer object is lesser than the second one.

-1