根据比较器排序,然后比较未给出预期结果

问题描述 投票:0回答:1

我有3个比较器,需要根据这些比较器对集合进行排序。比较器的添加方式使其需要根据一个属性进行排序,然后根据另一个属性进行排序,依此类推。

我的比较器看起来像这样

Comparator<Employee> a =Comparator.nullsLast(Comparator.comparing(Employee::getProduct(),Comparator.nullsLast(Comparator.naturalOrder())));

Comparator<Employee> b =Comparator.nullsLast(Comparator.comparing(Employee::getColor(),Comparator.nullsLast(Comparator.naturalOrder())));

List list=new ArrayList<>();
list.add(a);
list.add(b);

Comparator<Employee> first=list.get(0);
for(int i=1;i<list.size();i++){
Comparator<Employee> sec=first.thenComparing(list.get(i));
first=sec;
}

Collections.sort(employees,first);

[基本上,我试图将product的空值,然后将color的空值推到末尾。但是在我的结果中,我得到了介于两者之间的空值。我了解使用thenComparing API是错误的。有人可以照亮吗?

我的结果是这样的

| product | color |
|---------|-------|
| apple   | red   |
| apple   | red   |
| apple   | null  |
| apple   | null  |
| apple   | null  |
| apple   | null  |
| apple   | red   |
| apple   | red   |
| apple   | red   |
| apple   | null  |

您可以看到color属性中的空值介于两者之间,我需要将其推到末尾。怎么做?

java-8 comparator
1个回答
0
投票

这应该可以解决问题。

List<Employee> sorted = employees.stream().sorted(Comparator
    .comparing(Employee::getProduct, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(
        Comparator.comparing(Employee::getColor, Comparator.nullsLast(Comparator.naturalOrder()))))
    .collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.