java sortedlist 固定容量_Java8 使用 stream().sorted()对List集合进行排序

集合对像定义

集合对象以学生类(StudentInfo)为例,有学生的基本信息,包括:姓名,性别,年龄,身高,生日几项。

使用stream().sorted()进行排序,需要该类实现 Comparable接口,该接口只有一个方法需要实现,如下:

publicintcompareTo(T o);

有关compareTo方法的实现说明,请参考:Java 关于重写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);//按年龄排序(Integer类型)List studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());//排序后输出StudentInfo.printStudents(studentsSortName);

结果如下图:

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

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

结果如下图:

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

//排序前输出 StudentInfo.printStudents(studentList);

//按年龄排序(Integer类型)List studentsSortName = studentList.stream()

.sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))

.collect(Collectors.toList());

//排序后输出StudentInfo.printStudents(studentsSortName);

结果如下图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值