1. 程式人生 > 實用技巧 >使用 Stream 流對集合排序,包含對空屬性的處理

使用 Stream 流對集合排序,包含對空屬性的處理

在業務中有可能要對資料庫查詢出來的資料進行過濾,這樣資料庫的排序功能就不能用了,得手寫了,Java 8 的 Stream 流提供了很好的排序方法。

假如我們要對 Person 類陣列進行排序

@Data
public class Person {
    private String name;
    private Integer age;
    private Integer rank;
    public Person() {}
    public Person(String name, Integer age, Integer rank) {
        this.name = name;
        this.age = age;
        this.rank = rank;
    }
}

建立 Person 物件並新增到 List 集合中

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class OrderStreamTest {
    public static void main(String[] args) {
        Person p1 = new Person("zhang",60,1);
        Person p2 = new Person("li",11,2);
        Person p3 = new Person("w",13,3);

        List<Person> personList = new ArrayList<>();
        personList.add(p1);
        personList.add(p2);
        personList.add(p3);

        // 1. 只對一個屬性進行排序(數子)將陣列變成Stream 流 -> 呼叫 sorted 方法 -> 方法內傳入對比規則,用容器物件的屬性作為入參作為排序依據,預設升序,需要倒敘的話後面呼叫.reversed() 方法
        List<Person> collect1 = personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
        //List<Person> collect1 = personList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());
        collect1.forEach(System.out::println);
        // 2. 只對一個屬性進行排序(數字)該屬性有為 null 的情況會報錯  Exception in thread "main" java.lang.NullPointerException
        // 解決辦法時在 Comparator.comparing()入參多加一個nullsLast()的方法,用例出來null的情況,也可以時 nullsFirst 表示為空的排到前面
        Person p4 = new Person();
        p4.setName("ezha");
        personList.add(p4);
        List<Person> collect2 = personList.stream().sorted(Comparator.comparing(Person::getAge,Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        //List<Person> collect2 = personList.stream().sorted(Comparator.comparing(Person::getAge,Comparator.nullsFirst(Integer::compareTo))).collect(Collectors.toList());
        collect2.forEach(System.out::println);
        // 3. 對多個屬性進行排序,在比較後面加上 thenComparing 方法
        List<Person> collect3 = personList.stream().sorted(Comparator.comparing(Person::getAge,Comparator.nullsLast(Integer::compareTo)).thenComparing(Person::getName)).collect(Collectors.toList());
        collect3.forEach(System.out::println);
        // 4. 對多個屬性進行排序並忽略 null 值的屬性,寫法和前面的邏輯一樣,看程式碼
        List<Person> collect4 = personList.stream().sorted(Comparator.comparing(Person::getAge,Comparator.nullsLast(Integer::compareTo)).thenComparing(Person::getName,Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());
        collect4.forEach(System.out::println);
    }
}