在業務中有可能要對數據庫查詢出來的數據進行過濾,這樣數據庫的排序功能就不能用了,得手寫了,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);
}
}