This method returns a null-friendly comparator that considers null to be greater than non-null. When both are null
, they are considered equal. If both are non-null, the specified Comparator
is used to determine the order.
The specified comparator can be null, in that case returned comparator considers all non-null values to be equal.
package com.logicbig.example.comparator;
import java.util.Arrays;
import java.util.Comparator;
public class NullsLastExample {
public static void main(String... args) {
String[] strings = {"banana", "orange", null, "apple", null};
System.out.printf("before sort: %s%n", Arrays.toString(strings));
Arrays.sort(strings, Comparator.nullsLast(Comparator.naturalOrder()));
System.out.printf("after sort: %s%n", Arrays.toString(strings));
}
}
Output
before sort: [banana, orange, null, apple, null]
after sort: [apple, banana, orange, null, null]