'compareTo: treat two nulls as equal
I would like my compare method to work so that in the case where field1 == null in both objects, comparation would not be determined, but field2 would be checked, and so on. How to do it in the simplest way? The method below does not work well: when the fields from both objects are null, the comparison is always determined (without Ordering.natural().NullsFirst() I get NPE):
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public class MyClass implements Comparable<MyClass> {
String field1;
Integer field2;
String field3;
@Override
public int compareTo(MyClass myClass) {
return ComparisonChain.start()
.compare(field1, myClass.field1, Ordering.natural().nullsFirst())
.compare(field2, myClass.field2, Ordering.natural().nullsFirst())
.compare(field3, myClass.field3, Ordering.natural().nullsFirst())
.result();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
