Richard Avalos Richard Avalos - 1 year ago 107
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.

Answer Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download