When Collections.sort() encounters null elements in a list, it typically throws a NullPointerException because the sorting algorithm needs to compare elements to determine their order. Since null does not have any comparison behavior, Java cannot perform compareTo() operations on it, causing the sort process to fail.
Consider a list of employee names where some records are missing and represented as null. Directly calling Collections.sort() will fail. Using Comparator.nullsLast() can place all null values at the end of the sorted list.
import java.util.*;
public class NullSortingExample {
public static void main(String[] args) {
List<String> names = Arrays.asList(
"John",
null,
"Alice",
"Bob"
);
names.sort(Comparator.nullsLast(String::compareTo));
System.out.println(names);
}
}[Alice, Bob, John, null]A concise interview answer is: "If Collections.sort() is used on a list containing null elements, it usually throws a NullPointerException because null values cannot be compared. To handle such cases, use a custom Comparator such as Comparator.nullsFirst() or Comparator.nullsLast(), or remove null values before sorting."
Last updated: 11 November 2026
Previous question: How does Collections.sort() work internally?
Next question: Can you sort a list of custom objects using Collections.sort() without providing a Comparator?