I keep getting a nullpointerexception
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>() {
@Override
public int compare(UserModel c1, UserModel c2) {
return c1.getProfile().getFirstName().toLowerCase()
.compareTo(c2.getProfile().getFirstName().toLowerCase());
}
};
Collections.sort(users, Ordering.from(firstName_comparator).nullsLast());
This specific line throws the nullpointerexception
:
.compareTo(c2.getProfile().getFirstName().toLowerCase());
Its because getProfile()
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 =
Ordering.natural()
.nullsFirst()
.onResultOf(model -> c1.getProfile() == null? null : c1.getProfile().getFirstName().toLowerCase());