stream().sorted()实现排序(升序、降序、多字段排序)

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;

@Override

public int compareTo(Student ob) {

return name.compareTo(ob.getName());

}

@Override

public 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));

}

}

@Override

public 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());