Java8 使用 stream().sorted()对List集合进行排序

论坛 期权论坛 脚本     
匿名技术用户   2021-1-7 11:06   48   0

1、声明一个测试对象

import java.time.LocalDate;
import java.util.List;
import lombok.Data;

@Data
public class StudentInfo{

    //名称
    private String name;

    //性别 true男 false女
    private Boolean gender;

    //年龄
    private Integer age;

    //身高
    private Double height;

    //出生日期
    private LocalDate birthday;

}

2、添加一些测试数据

//测试数据,请不要纠结数据的严谨性
List<StudentInfo> studentList = new ArrayList<>();
studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));
studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));

使用年龄进行升序排序

//排序前输出
StudentInfo.printStudents(studentList);
//按年龄排序(Integer类型)
List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());
//排序后输出
StudentInfo.printStudents(studentsSortName);

排序后结果

使用年龄进行降序排序(使用reversed()方法)

//排序前输出
StudentInfo.printStudents(studentList);
//按年龄排序(Integer类型)
List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());
//排序后输出
StudentInfo.printStudents(studentsSortName);

排序后结果

使用年龄进行降序排序,年龄相同再使用身高升序排序

//排序前输出
        StudentInfo.printStudents(studentList);
        //按年龄排序(Integer类型)
        List<StudentInfo> studentsSortName = studentList.stream()
                .sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))
                .collect(Collectors.toList());
        //排序后输出
        StudentInfo.printStudents(studentsSortName);

排序后结果

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP