What is the Comparator.nullsLast method in Java?
Overview
nullsLast is a static method of the Comparator interface that is used to return a Comparator that considers null elements to be greater than non-null elements.
The Comparator.nullsLast method takes a Comparator as a parameter, which is used to compare the non-null elements. If the passed comparator is null, then the non-null values are considered to be equal.
Given two inputs and a non-null Comparator as the parameter, the following scenarios are possible:
- When both the inputs are
null, the inputs are considered equal. - When both the inputs are non-null, the supplied
Comparatoris used for comparison. - When one of the inputs is
nulland the other is non-null, then thenullinput is considered to be greater than the non-null input.
The Comparator interface is defined in the java.util package. To import the Comparator interface, we use the following import statement:
import java.util.Comparator;
Syntax
public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator)
Parameters
Comparator<? super T> comparator: TheComparatorthat is used to compare non-null values.
Return value
This method returns a Comparator.
Code
import java.util.Arrays;import java.util.Comparator;public class Main{public static void main(String[] args) {// Collection of stringsString[] strings = {null, "hello", "educative", null, "edpresso"};// print the string collectionSystem.out.println("Before sorting: " + Arrays.toString(strings));// Using the nullsLast method to sort the arrayArrays.sort(strings, Comparator.nullsLast(Comparator.naturalOrder()));// print the sorted arraySystem.out.println("After sorting: " + Arrays.toString(strings));}}