1. Introduction
In Java, when sorting collections using a Comparator, handling null values can be tricky. By default, using a comparator on null values can throw a NullPointerException. Therefore, it’s important to handle null values explicitly to ensure a smooth and expected sorting order. In this post, we will demonstrate how to handle null values while sorting, using Java’s Comparator interface.
2. Program Steps
1. Define a Person class with attributes like name.
2. Create a list of Person objects, some of which are null.
3. Define a comparator to sort by name and handle null values.
4. Sort the list of persons using the comparator.
5. Print the sorted list.
3. Code Program
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class Person {
String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class NullHandlingComparatorDemo {
public static void main(String[] args) {
// Create a list of persons with null values
List<Person> persons = Arrays.asList(
new Person("John"),
null,
new Person("Jane"),
new Person("Doe"),
null
);
System.out.println("Original list: " + persons);
// Sort persons by name, handling null values
persons.sort(Comparator.nullsFirst(Comparator.comparing(Person::getName)));
System.out.println("Sorted with nulls first: " + persons);
}
}
Output:
Original list: [John, null, Jane, Doe, null] Sorted with nulls first: [null, null, Doe, Jane, John]
4. Step By Step Explanation
1. We define a Person class with an attribute name and provide a suitable toString() method for easy printing.
2. In the main method, we create a list of Person objects, including some null values.
3. We then define a comparator using Comparator.comparing() to sort persons based on their names. To handle null values, we wrap this comparator with Comparator.nullsFirst(), which ensures that null values are treated as being less than any non-null value.
4. We then sort the list of persons using the defined comparator.
5. The output shows that the list is sorted with null values first, followed by persons sorted alphabetically by name.
This way, by using Java's built-in nullsFirst and nullsLast methods, we can seamlessly handle null values while sorting collections.