Comparator nullsLast() method in Java with examples
The nullsLast (java.util.Comparator) method returns comparator that is a null-friendly comparator and considers null values greater than non-null. The null first operates by the following logic:
- The null element is considered to be greater 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 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> nullsLast (Comparator<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 greater than non-null and compares non-null objects with the supplied Comparator.
Below programs illustrate nullsLast(java.util.Comparator) method:
The output printed on console of IDE is shown below.
The output printed on console is shown below.