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?
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())
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With