Comparator nullsFirst() method in Java with examples
The nullsFirst(java.util.Comparator) method returns comparator that is a null-friendly comparator and considers null values to be less than non-null. The null first operates by the following logic:
- The null element is considered to be less than non-null.
- When both elements are null, then they are considered equal.
- When both elements are non-null, the specified Comparator determines the order.
- If the specified comparator is null, then the returned comparator considers all non-null elements equal.
- The returned comparator is serializable if the specified comparator is serializable.
static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)
Parameters: This method accepts a single parameter comparator which is a Comparator for comparing non-null values
Return value: This method returns a comparator that considers null to be less than non-null and compares non-null objects with the supplied Comparator.
Below programs illustrate nullsFirst(java.util.Comparator) method:
The output printed on console of IDE is shown below.
The output printed on console is shown below.