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
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