When using Collection.sort in Java what should I return when one of the inner objects is null
Example:
Collections.sort(list, new Comparator<MyBean>() {
public int compare(MyBean o1, MyBean o2) {
return o2.getDate().compareTo(o1.getDate());
}
});
Lets say o2 is not null but o2.getDate() it is, so should I return 1 or -1 or 0 when adding a null validation?
We are sorting using the nullsFirst() method, after sorting, null values will come in the start and then the sorting list of employees will come sorted by date of birth. To sort on natural order, after ordering null values, use Comparator. nullsFirst( Comparator. naturalOrder() ).
Comparator) method returns comparator that is a null-friendly comparator and considers null values greater than non-null. The null first operates by the following logic: The null element is considered to be greater than non-null. When both elements are null, then they are considered equal.
Naturally, it's your choice. Whatever logic you write, it will define sorting rules. So 'should' isn't really the right word here.
If you want null to appear before any other element, something like this could do
public int compare(MyBean o1, MyBean o2) {
if (o1.getDate() == null) {
return (o2.getDate() == null) ? 0 : -1;
}
if (o2.getDate() == null) {
return 1;
}
return o2.getDate().compareTo(o1.getDate());
}
In Java 8 you can also use nullsFirst()
:
Comparator.nullsFirst(Date::compareTo).compare(dateOne, dateTwo);
Or nullsLast()
:
Comparator.nullsLast(Date::compareTo).compare(dateOne, dateTwo);
These methods will either sort null
to the beginning or to the end. There is no wrong or right whether you consider null
bigger or smaller than another objects. This is totally up to you, as others stated already.
Depending on whether the object is null, or the content of the object is null.
The object is null:
import static java.util.Comparator.*;
List<Data> listOfData = Arrays.asList(
new Data("foo"),
null,
new Data("bar"),
new Data("nyu"));
listOfData.sort(nullsFirst(comparing(Data::getValue)));
listOfData.forEach(System.out::println);
//OUTPUT:
// null
// Data(bar)
// Data(foo)
// Data(nyu)
The content of the object is null:
List<Data> listOfData = Arrays.asList(
new Data("foo"),
new Data(null),
new Data("bar"),
new Data("nyu"));
listOfData.sort(nullsFirst(
comparing(Data::getValue, nullsFirst(naturalOrder()))));
listOfData.forEach(System.out::println);
//OUTPUT:
// Data(null)
// Data(bar)
// Data(foo)
// Data(nyu)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With