集合对象以学生类(StudentInfo)为例,包含学生基本信息:姓名,性别,年龄,身高,生日。使用stream().sorted()进行排序要求StudentInfo类实现Comparable接口,其中需实现compareTo方法。具体实现如以下代码:StudentInfo类定义 添加测试数据 示例测试数据如下://测试数据,请忽略数据严谨性List studentList =n...
Java8 使用 stream.sorted对List集合进行排序
集合对像定义
集合对象以学生类(StudentInfo)为例,包含学生基本信息:姓名,性别,年龄,身高,生日。
使用stream().sorted()进行排序要求StudentInfo类实现Comparable接口,其中需实现compareTo方法。
具体实现如以下代码:
StudentInfo类定义
添加测试数据
示例测试数据如下:
//测试数据,请忽略数据严谨性List studentList =newArrayList<>();
studentList.add(newStudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
studentList.add(newStudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));
studentList.add(newStudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
studentList.add(newStudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));
排序操作
使用年龄进行升序排序:
//排序前输出StudentInfo.printStudents(studentList);//按年龄升序排序(List)List studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());//排序后输出StudentInfo.printStudents(studentsSortName);
结果展示
使用年龄进行降序排序(使用reversed()方法):
//排序前输出StudentInfo.printStudents(studentList);//按年龄降序排序(List)List studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());//排序后输出StudentInfo.printStudents(studentsSortName);
结果展示
使用年龄进行降序排序,年龄相同再使用身高升序排序:
//排序前输出StudentInfo.printStudents(studentList);
//按年龄降序排序,年龄相同身高升序排序(List)List studentsSortName = studentList.stream()
.sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))
.collect(Collectors.toList());
结果展示2024-10-11