69

I've implemented a sorting on a collection using a lambda expression for the comparison. I have to check for null values, so I came up with this solution for the comparator

(a,b)->(
    (a.getStartDate() == null) 
        ? ( (b.getStartDate() == null) ? 0 : -1)
        : ( (b.getStartDate() == null)?1:a.getStartDate().compareTo(b.getStartDate()) )
);

I've already checked some questions, like this, but they all refer to pre-lambda code.

Do java lambda expressions give me the chance to avoid the two 'if' statements? Can I perform the task in a cleaner way?

Community
  • 1
  • 1
Gabber
  • 5,152
  • 6
  • 35
  • 49
  • See also http://stackoverflow.com/questions/36361156/null-safe-date-comparator-for-sorting-in-java-8-stream and http://stackoverflow.com/questions/39518961/comparator-based-on-different-nullable-fields-of-an-object and http://stackoverflow.com/questions/26350996/java-8-comparator-nullsfirst-naturalorder-confused – Tunaki Oct 06 '16 at 08:57
  • Thank you @Tunaki !! deleting the question - edit: can't do this because it is answered... – Gabber Oct 06 '16 at 09:01

1 Answers1

200

There are default implementations within Comparator you can use: nullsFirst or nullsLast:

Comparator.comparing(YourObject::getStartDate, 
  Comparator.nullsFirst(Comparator.naturalOrder())
)
flo
  • 9,713
  • 6
  • 25
  • 41