Monday, February 10, 2014

No Null Checks: Use Comparator null handling

I need to sort on a field that could be null in some object instances.  Use Comparator null handling to compare instances that can be null.

In this compareTo method I have some employees without middle names.  So, if the first and last name are the same the sort will take into account the middle name - which could be null :-(

I'm going to clean-up this method by using the Comparator class from Java 8.

The Comparator defines a fluent interface that is used to build a comparator for multiple members of a class.  The secret sauce is the easy way it sorts nulls before or after non-null values - when both instances are null they are considered equal.

This update creates a separate comparator instance that is then used in the compareTo method. The null check is tucked away neatly within the Comparator.nullsFirst method. Also note the use of method literals to define the members of the Employee classes used for the compare.

No comments:

Post a Comment