1 自然排序
sorted():自然排序,流中元素需实现Comparable接口
package com.entity;import lombok.*;@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Comparable<Student> {private int id;private String name;private int age;@Overridepublic int compareTo(Student ob) {return name.compareTo(ob.getName());}@Overridepublic boolean equals(final Object obj) {if (obj == null) {return false;}final Student std = (Student) obj;if (this == std) {return true;} else {return (this.name.equals(std.name) && (this.age == std.age));}}@Overridepublic int hashCode() {int hashno = 7;hashno = 13 * hashno + (name == null ? 0 : name.hashCode());return hashno;}
}
2 定制排序
sorted(Comparator com):定制排序,自定义Comparator排序器
3 升序
3.1 自然排序
list = list.stream().sorted().collect(Collectors.toList());
3.2 定制排序
根据年龄升序排序。
list = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
4 降序
4.1 自然排序
使用Comparator 提供的reverseOrder() 方法
list = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
4.2 定制排序
根据年龄降序排序。
list = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
5 多字段排序
先按姓名升序,姓名相同则按年龄升序。
list = list.sorted(Comparator.comparing(Student::getName).thenComparing(Student::getAge)).collect(Collectors.toList());
旭东怪的个人空间_哔哩哔哩_Bilibili旭东怪,人生低谷不可怕,可怕的是坚持不到人生转折点的那一天;旭东怪的主页、动态、视频、专栏、频道、收藏、订阅等。哔哩哔哩Bilibili,你感兴趣的视频都在B站。https://space.bilibili.com/484264966?spm_id_from=333.1007.0.0