【问题标题】:Wrong order during sorting at first by predefined order, and then by natural order using Comparator method thenComparing()排序过程中的错误顺序首先按预定义顺序,然后使用 Comparator 方法按自然顺序 thenComparing()
【发布时间】:2021-12-16 09:59:54
【问题描述】:

我有一个简单的对象类:

public class Employee {
    String name;
    String secondName;
 // Conctructor, getters & setters
}

员工名单:

        List<Employee> employees = new ArrayList<>(Arrays.asList(
                new Employee("Jake",  "Bbb"),
                new Employee("Ann",   "Aaa"),
                new Employee("Ivy",   "Bbb"),
                new Employee("Ivy",   "Aaa"),
                new Employee("Jake",  "Aaa"),
                new Employee("Tom",   "Iii"),
                new Employee("Neil",  "Xxx"),
                new Employee("Keith", "Ooo"),
                new Employee("Tom",   "Rrr")
        ));

我想先按预定义的 secondNames 顺序对它们进行排序,而不是按名称的自然顺序:

List<String> definedOrder = Arrays.asList("Iii", "Bbb", "Aaa");

这样:

employees.sort(
        Comparator.comparing((Employee e) -> definedOrder.indexOf(e.getSecondName()))
                .thenComparing(Employee::getName));

for (Employee em : employees){
     System.out.println(em.getSecondName() + " / " + em.getName());
}

我建议先接收列表中的预定义对象,然后是其余对象:

Iii / Tom
Bbb / Ivy
Bbb / Jake
Aaa / Ann
Aaa / Ivy
Aaa / Jake
Ooo / Keith
Xxx / Neil
Rrr / Tom

但我收到的对象首先按自然顺序按 names 排序(使用 thenComparing() 方法),然后按 secondNames 进行预定义比较:

Ooo / Keith
Xxx / Neil
Rrr / Tom
Iii / Tom
Bbb / Ivy
Bbb / Jake
Aaa / Ann
Aaa / Ivy
Aaa / Jake

【问题讨论】:

    标签: java sorting comparator


    【解决方案1】:

    当在definedOrder 中找不到第二个名字时,您错过了definedOrder.indexOf(e.getSecondName()) 返回-1

    这就是为什么 OooXxxRrr 出现在 IiiBbbAaa 之前的原因。

    并且,由于 OooXxxRrr 对于 comparing 而言都共享相同的值 (-1),它们之间按 thenComparing(Employee::getName)) 排序。


    要解决此问题,您可以检查 definedOrder.indexOf(e.getSecondName()) 是否返回 -1,如果是,则返回 Integer.MAX_VALUE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 2022-01-01
      • 1970-01-01
      相关资源
      最近更新 更多