Reputation: 2797
I have to sort a Collection by different String attributes that might be empty (""
) or even null
. Both values are allowed and have to be treated equally.
I solved this issue by using a method, that checks each String for null
and returns an empty String, when null
is found.
So far my Comparator looks basicly like this
public class MyComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
// ... some logical stuff like e.g.
return rein(o1.getSomeValue()).compareTo(rein(o2.getSomeValue());
}
private String rein(String str) {
return str == null ? "" : str;
}
}
I wonder if this design is considered to be ok or if there are reason against it? If it is not ok, what else may I do to fulfil my requirements? All those (in most cases unneccessary) function calls looks ugly to me, as we are talking about approximately 1/1000 cases. So I wonder if there is a more elegant solution?
Upvotes: 0
Views: 114
Reputation: 603
With Java 8 one can rewrite it a bit more concise in functional style using Comparator.comparing(keyExtractor) and other factory methods from Comparator to chain / compose comparators. But you still have to handle the null
case otherwise a NullPointerException
will arise.
null
and ""
are treated equally:import static java.util.Comparator.comparing;
Comparator<MyObject> bySomeValue =
comparing(obj -> rein(obj.getSomeValue()));
Note: nullToEmpty()
would be a more suitable name than rein()
.
null
ordering can be explicitly specified by available nullsFirst() or nullsLast() decoratorsimport static java.util.Comparator.comparing;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;
Comparator<MyObject> bySomeValue =
comparing(MyObject::getSomeValue, nullsLast(naturalOrder()));
Upvotes: 0
Reputation: 797
Nothing wrong here. If you omit 'rein' method you will get NullPointerException in case when o1.getSomeValue() returns null. So this check is necessary for correct compare method working. It's hard to imagine more elegant solution.
Upvotes: 2