Richard Avalos Richard Avalos - 8 months ago 41
Java Question

Cant sort null with comparator

I keep getting a

when I try to sort users where a certain user has a null value in his profile. I was under the impression
Google Collection
would handle these null values, but it doesnt seem to work.

This is the code I use:

Comparator<UserModel> firstName_comparator = new Comparator<UserModel>() {
public int compare(UserModel c1, UserModel c2) {
return c1.getProfile().getFirstName().toLowerCase()
Collections.sort(users, Ordering.from(firstName_comparator).nullsLast());

This specific line throws the


Its because
is null.
How can I fix this? I want to be able to sort my users with null values.


No, Guava won't ignore your NullPointerException. You're providing a Comparator, and this comparator is supposed to respect the Comparator contract. Throwing NullPointerException is not part of the contract.

String firstName1 = c1.getProfile() == null? null : c1.getProfile().getFirstName().toLowerCase();
String firstName2 = c2.getProfile() == null? null : c1.getProfile().getFirstName().toLowerCase();

return Ordering.natural().nullsFirst().compare(firstName1, firstName2);
// or nullsLast(), depending on what you prefer

Or, simpler:

Comparator<UserModel> comparator = 
            .onResultOf(model -> c1.getProfile() == null? null : c1.getProfile().getFirstName().toLowerCase());