繁体   English   中英

首先按预定义顺序排序,然后按自然顺序使用 Comparator 方法 thenComparing() 排序时顺序错误

[英]Wrong order during sorting at first by predefined order, and then by natural order using Comparator method thenComparing()

我有一个简单的对象类:

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

但是我收到的对象首先按name s按自然顺序排序,(使用 thenComparing() 方法),然后通过secondName s从预定义的比较中收到

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

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

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

并且,由于OooXxxRrr都共享相同的值 ( -1 ) 以进行comparing ,因此它们之间按thenComparing(Employee::getName))排序。


要修复此行为,您可以检查definedOrder.indexOf(e.getSecondName())返回-1 ,如果是,则返回Integer.MAX_VALUE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM