How to simplify a null-safe compareTo() implementation? How to simplify a null-safe compareTo() implementation? java java

How to simplify a null-safe compareTo() implementation?


You can simply use Apache Commons Lang:

result = ObjectUtils.compare(firstComparable, secondComparable)


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);}


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