java对List<Student>或者List<Map>进行排序

对List(Map)进行排序


 public void sortLastOnlineList(CloudRInfoPo cloudRInfoPo, List<Map<String, Object>> result) {
        if (!StringUtils.isEmpty(cloudRInfoPo.getDuration()) || "desc".equals(cloudRInfoPo.getSort())) {
            //正序
            result.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("lastOnlineTime"))));  
        }
        if (!StringUtils.isEmpty(cloudRInfoPo.getDuration()) || "asc".equals(cloudRInfoPo.getSort())) {
             //倒序
            result.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("lastOnlineTime"))).reversed());
        }
    }

对List<Student>进行排序

 
List<Student> students = new ArrayList<>();
Student student1 = new Student("六年级","Math","小张",1D);
students.add(student1);
Student student2 = new Student("三年级上","English","小钱",8D);
students.add(student2);
Student student3 = new Student("五年级","Chinese","小孙",6D);
students.add(student3);
 
倒序
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getMark).reversed()).collect(Collectors.toList());
 
控制台:
排序前:1.0|8.0|6.0|
排序后:8.0|6.0|1.0|
 
正序
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getMark)).collect(Collectors.toList());
 
控制台:
排序前:1.0|8.0|6.0|
排序后:1.0|6.0|8.0|
 

需要注意的是:

排序字段为null时会报错!!!

需要对null值进行处理或过滤掉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值