How to handle nulls when using Java collection sort

Viewed 61534

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?

6 Answers

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 comparing two property, attr1 natural order, attr2 reverse order, and attr2 can be null:

datas.sort(comparing(Data::getAttr1, naturalOrder()).
        thenComparing(Data::getAttr2, nullsLast(reverseOrder())));
Related