我们在处理数据的时候经常会需要进行排序后再返回给前端调用,比如按照时间升序排序,前端展示数据就是按时间先后进行排序。 这里可以运用stream的
sorted()方法来进行自定义的排序

 用法

 这里举例数据是一个list集合,List<Data>list,Data实体类中有许多属性,其中有时间字段,month
月份,那我们用stream().sorted()方法排序时,因为元素是类引用类型,需要自定义一个比较器Comparator,按month月份进行升序排序。代码如下。
list.stream().sorted(Comparator.comparing(o->new
Integer(o.getMonth()))).collect(Collectors.toList());
 注意:这里比较器里面参数用了Lambda 表达式,new Integer(o.getMonth())
,这种封装成Integer类型的是因为我们设计的Data实体类中的month属性是String类型,并非Integer,转换成Integer是为了后续做月份遍历判断,如果属性是Integer
Month,则可以比较器中可以直接定义类的方法引用 如下:

list.stream().sorted(Comparator.comparing(Data::getMonth).collect(Collectors.toList());

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信