Close

Java Utils - Objects.compare() Examples

Java Utils Java Java API 


Class:

java.util.Objects

java.lang.Objectjava.lang.Objectjava.util.Objectsjava.util.ObjectsLogicBig

Method:

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

This method returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned.If one of the arguments is null, a NullPointerException may be thrown depending on how the specified Comparator treats nulls.


Examples


package com.logicbig.example.objects;

import java.util.Objects;

public class CompareExample {

public static void main(String... args) {
String s1 = "testStr";
String s2 = "testStr";
int i = Objects.compare(s1, s2, String::compareTo);
System.out.println(i);

//equivalent to
int i2 = s1.compareTo(s2);
System.out.println(i2);
}
}

Output

0
0




Objects#compare is useful when an object is not comparable:

package com.logicbig.example.objects;

import java.util.Comparator;
import java.util.Objects;

public class CompareExample2 {

public static void main(String... args) {
MyClass o1 = new MyClass(5);
MyClass o2 = new MyClass(5);

int i = Objects.compare(o1, o2, Comparator.comparingInt(MyClass::getId));
System.out.println(i);

MyClass o3 = new MyClass(6);
int i2 = Objects.compare(o1, o3, Comparator.comparingInt(MyClass::getId));
System.out.println(i2);
}

private static class MyClass {
int id;

public MyClass(int id) {
this.id = id;
}

public int getId() {
return id;
}
}

}

Output

0
-1




package com.logicbig.example.objects;

import java.util.Comparator;
import java.util.Objects;

public class CompareExample3 {

public static void main(String... args) {
int i = Objects.compare(null, null, Comparator.naturalOrder());
System.out.println(i);
}
}

Output

0




If only one of them is null:

package com.logicbig.example.objects;

import java.util.Comparator;
import java.util.Objects;

public class CompareExample4 {

public static void main(String... args) {
int i = Objects.compare("test", null, Comparator.naturalOrder());
System.out.println(i);
}
}

Output

Caused by: java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1155)
at java.lang.String.compareTo(String.java:111)
at java.util.Comparators$NaturalOrderComparator.compare(Comparators.java:52)
at java.util.Comparators$NaturalOrderComparator.compare(Comparators.java:47)
at java.util.Objects.compare(Objects.java:183)
at com.logicbig.example.objects.CompareExample4.main(CompareExample4.java:15)
... 6 more




See Also