How to simplify a null-safe compareTo() implementation?
Solution 1:
You can simply use Apache Commons Lang:
result = ObjectUtils.compare(firstComparable, secondComparable)
Solution 2:
Using Java 8:
private static Comparator<String> nullSafeStringComparator = Comparator
.nullsFirst(String::compareToIgnoreCase);
private static Comparator<Metadata> metadataComparator = Comparator
.comparing(Metadata::getName, nullSafeStringComparator)
.thenComparing(Metadata::getValue, nullSafeStringComparator);
public int compareTo(Metadata that) {
return metadataComparator.compare(this, that);
}
Solution 3:
I would implement a null safe comparator. There may be an implementation out there, but this is so straightforward to implement that I've always rolled my own.
Note: Your comparator above, if both names are null, won't even compare the value fields. I don't think this is what you want.
I would implement this with something like the following:
// primarily by name, secondarily by value; null-safe; case-insensitive
public int compareTo(final Metadata other) {
if (other == null) {
throw new NullPointerException();
}
int result = nullSafeStringComparator(this.name, other.name);
if (result != 0) {
return result;
}
return nullSafeStringComparator(this.value, other.value);
}
public static int nullSafeStringComparator(final String one, final String two) {
if (one == null ^ two == null) {
return (one == null) ? -1 : 1;
}
if (one == null && two == null) {
return 0;
}
return one.compareToIgnoreCase(two);
}
EDIT: Fixed typos in code sample. That's what I get for not testing it first!
EDIT: Promoted nullSafeStringComparator to static.