gpt4 book ai didi

java - 末尾带有 null 的集合比较器

转载 作者:行者123 更新时间:2023-11-30 06:23:36 27 4
gpt4 key购买 nike

我有一些User对象,可以有nameemail,我希望它们按名称排序,然后按电子邮件排序,但首先显示名称不为空的用户。我正在尝试这样:

 Collections.sort(usersList, new Comparator<User>() {
@Override
public int compare(User obj1, User obj2) {
int res = 0;

//to make sure null names at the end

if (obj1.getFullName() == null && obj2.getFullName() == null)
res = 0;

if (obj1.getFullName() == null)
res = 1;

if (obj2.getFullName() == null)
res = -1;

//logic for name sorting then email sorting

if (obj1.getFullName() != null && obj2.getFullName() != null)
res = obj1.getFullName().compareTo(obj2.getFullName());

if (res == 0)
res = obj1.getEmail().compareTo(obj2.getEmail());

return res;
}
});

因此,我首先得到姓名,但按电子邮件而不是姓名排序。

最佳答案

这可以通过 Java-8 的 Comparator 轻松完成实用程序:

List<User> users = Arrays.asList(new User("pete", "pete@email"), new User(null, null), new User("alex", null), new User(null, "email"));

Collections.sort(users, Comparator.comparing(User::getName, Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(Comparator.comparing(User::getEmail, Comparator.nullsLast(Comparator.naturalOrder()))));

System.out.println(users);

输出:

[
User{name='alex', email='null'},
User{name='pete', email='pete@email'},
User{name='null', email='email'},
User{name='null', email='null'}
]

关于java - 末尾带有 null 的集合比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47657216/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com