我不断收到 nullpointerexception
当我尝试对某个用户的个人资料中具有空值的用户进行排序时。我的印象是Google Collection
会处理这些空值,但它似乎不起作用。
这是我使用的代码:
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());
<小时/>
该特定行抛出 nullpointerexception
:
.compareTo(c2.getProfile().getFirstName().toLowerCase());
因为getProfile()
为空。
我该如何解决这个问题?我希望能够使用空值对用户进行排序。
最佳答案
不,Guava 不会忽略您的 NullPointerException。您正在提供一个比较器,并且该比较器应该遵守比较器契约(Contract)。抛出 NullPointerException 不是契约的一部分。
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
或者更简单:
Comparator<UserModel> comparator =
Ordering.natural()
.nullsFirst()
.onResultOf(model -> c1.getProfile() == null? null : c1.getProfile().getFirstName().toLowerCase());
关于java - 无法使用比较器对 null 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38814741/