1. 程式人生 > >在Java中使用Collections.sort 依據多個欄位排序

在Java中使用Collections.sort 依據多個欄位排序

## 一、如何使用Collections工具類進行排序 使用Collections工具類進行排序主要有兩種方式: ### 1.物件實現Comparable介面,重寫compareTo方法 ```java /** * @author Hanstrovsky */ @Data @AllArgsConstructor public class Student implements Comparable { String name; int age; @Override public int compareTo(Object o) { Student stu = (Student) o; //this-引數:升序;引數-this:降序 return this.age - stu.age; } } ``` ```java /** * @author Hanstrovsky */ public class Test01 { public static void main(String[] args) { List stuList = new ArrayList<>(); stuList.add(new Student("abc", 17)); stuList.add(new Student("cab", 18)); Collections.sort(stuList); System.out.println(stuList); } } ``` ### 2.傳入一個比較器物件Comparator。 還是用上面的student,不去實現Comparable介面。 ```java /** * @author Hanstrovsky */ public class Test02 { public static void main(String[] args) { List stuList = new ArrayList<>(); stuList.add(new Student("abc", 19)); stuList.add(new Student("cab", 18)); Collections.sort(stuList, new Comparator() { @Override public int compare(Student o1, Student o2) { return o1.age - o2.age; } }); System.out.println(stuList); } } ``` ## 二、依據多個欄位排序 當需求要求先按第一個欄位排序,如果第一個欄位相同,則按第二個欄位排序,如果第二個相同,則按第三個欄位... 可以定義多個Comparator,並依次使用。 ```java /** * @author Hanstrovsky */ @Data @AllArgsConstructor public class Student { // 編號 private String id; // 身高 private int height; // 體重 private int weight; } ``` ```java /** * @author Hanstrovsky */ public class Test03 { public static void main(String[] args) { Student s1 = new Student("1", 180, 80); Student s2 = new Student("2", 175, 80); Student s3 = new Student("3", 175, 90); List students = new ArrayList<>(); students.add(s1); students.add(s2); students.add(s3); System.out.println("原始排序:" + students); //按照身高升序排序 Comparator byHeight = Comparator.comparing(Student::getHeight); //按照體重升序排序 Comparator byWeight = Comparator.comparing(Student::getWeight); //將list先按照"身高"升序再按照"體重"升序排列 students.sort(byHeight.thenComparing(byWeight)); //將list先按照"身高"升序再按照"體重"升序排列 System.out.println("優先身高:" + students); //將list先按照"體重"升序再按照"身高"升序排列 students.sort(byWeight.thenComparing(byHeight)); //將list先按照"身高"升序再按照"體重"升序排列 System.out.println("優先體重:" + students);