The nullsFirst()
method is used to return a Comparator
, which considers the null
elements to be lesser than the non-null elements.
It takes a Comparator
as a parameter, which is then used for the comparison of the non-null elements.
Given two inputs and a non-null comparator as the parameter, the following scenarios are possible:
First input | Second input | Behaviour |
---|---|---|
null | null | The inputs are considered equal. |
non-null | non-null | The supplied comparator is used for comparison. |
null | non-null | First input is considered to be less than the second input. |
non-null | null | Second input is considered to be less than the first input. |
The Comparator
interface is defined in the java.util
package. To import the Comparator
interface, we check the following import statement:
import java.util.Comparator;
public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)
Comparator<? super T> comparator
: This is the Comparator
that is used for comparing the non-null values.
This method returns a Comparator
which considers the null
elements to be lesser than the non-null elements.
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 nullsFirst method to sort the arrayArrays.sort(strings, Comparator.nullsFirst(Comparator.naturalOrder()));// print the sorted arraySystem.out.println("After sorting: " + Arrays.toString(strings));}}
null
and non-null values.Arrays.sort()
method and passing the Comparator.nullsFirst()
method as a parameter.