Java 8 lambda comparator with null value check
LambdaJava 8Lambda Problem Overview
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?
Lambda Solutions
Solution 1 - Lambda
There are default implementations within Comparator you can use: nullsFirst
or nullsLast
:
Comparator.comparing(YourObject::getStartDate,
Comparator.nullsFirst(Comparator.naturalOrder())
)