如何用Java对两件事情进行排序?

时间:2018-04-17 21:13:52

标签: java sorting

public static void main(String[] args) {

    ArrayList<Employee> unsorted = loadEmployee("NameList.csv", 100);


    Collections.sort(unsorted,(Employee o2, Employee o1)-> o1.getFirstName().compareTo(o2.getFirstName() ));


    unsorted.forEach((Employee)-> System.out.println(Employee));

按字母顺序打印名字。但是你如何先按ID排序名字呢? 我有Employee课程并且String ID, String firstName。 在这里学习Collections.sort

1 个答案:

答案 0 :(得分:2)

您正在寻找Comparator#thenComparing

使用Collections#sort

List<Employee> unsorted = loadEmployee("NameList.csv", 100);

Collections.sort(unsorted, Comparator.comparing(Employee::getFirstName)
                                     .thenComparing(Employee::getId));

unsorted.forEach(System.out::println);

使用流:

loadEmployee("NameList.csv", 100).stream()
                                 .sorted(Comparator.comparing(Employee::getFirstName)
                                                   .thenComparing(Employee::getId))
                                 .forEach(System.out::println);

首先按Employee的名字排序,如果不同Employee的两个名称相同,则按ID排序。