When using Collection.sort in Java what should I return when one of the inner objects is null
Example:
Collections.sort(list, new Comparator
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 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 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)