Java 8 lambda comparator with null value check

LambdaJava 8

Lambda 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())
)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGabberView Question on Stackoverflow
Solution 1 - LambdafloView Answer on Stackoverflow