Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to Sort in Java 8 with Nulls in the Data

I am trying to sort a list that I get by the comparator given. I am passing the comparator through the NullsLast method to get a Null-Friendly version of my comparator like the JavaDoc states. However, when I run the code I am still getting a Null Pointer Exception when I pass a String comparator to the method.

private <T> void sortWithDirection(List<T> details, boolean isAscending, Comparator<T> comparator){

    if(isAscending){
        details.sort(Comparator.nullsLast(comparator));
    } else {
        details.sort(Comparator.nullsLast(comparator.reversed()));
    }
}

List<UserDTO> users = new ArrayList<>();
sortWithDirection(users, false, Comparator.comparing(UserDTO::getName));

Am I using this method wrong? Is there a different way that I can prevent NPEs without removing them from the result set?

like image 206
wheelerswebservices Avatar asked Jan 29 '23 18:01

wheelerswebservices


1 Answers

nullsLast will handle the case of UserDTO being null. It will not save you from getName returning null. To handle null names, you would need to apply nullsLast before comparing:

details.sort(comparing(
    UserDTO::getName, 
    nullsLast(naturalOrder())
));

or, for reverse order:

details.sort(comparing(
    UserDTO::getName, 
    nullsLast(reverseOrder())
));
like image 101
Misha Avatar answered Feb 01 '23 06:02

Misha