对List集合中的对象进行按某个属性排序

谨以此文献给天上星

一 、通过code自然排序

resultList.sort((h1, h2) -> h1.getCode().compareTo(h2.getCode()));

二 、通过code反序排列

Comparator<ProomRealTimeOut> comparator = (h1, h2) -> h1.getCode().compareTo(h2.getCode());
resultList.sort(comparator.reversed());

注:换一下h1,h2顺序也可以实现反序

三 、通过code自然排序

Collections.sort(resultList, (v1, v2) -> v1.getCode().compareTo(v2.getCode()));

注:这种和本质上和第一种一样

四、通过code自然排序

List<ProomRealTimeOut> collect = resultList.stream().sorted((h1, h2) -> h1.getCode().compareTo(h2.getCode())).collect(Collectors.toList());

注:stream的排序不会操作原对象,必须收集排序结果。即collect为已排序List

 

以上方法均有无comparator参数的重载方法,方法默认使用List内对象的compare方法,即对象必须实现Comparable接口重写compareTo方法

 

############################################################################################################################################################################################

(h1, h2) -> h1.getCode().compareTo(h2.getCode())本质是通过Lambda 表达式实现了Comparator<T>函数式接口的compare方法,该方法有两个T型的入参即h1,h2,一个int型的出参即h1.getCode().compareTo(h2.getCode())

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值