快速处理集合 | Java8 新特性 好用的 Stream 表达式


个人记录
由于本人用的也不是很精通,所有做个记录,方便查阅

快速处理集合 | Java8 新特性 好用的 Stream 表达式


好用在哪?

准备工作,

在这里插入图片描述


一、从List 对象获取单个对象的某个字段的值

在这里插入图片描述

以上新的coinList就是list中每个AllCoinEntity对象的coin字段的值

二、List转map

Map<String, Long> collect = coinList.stream().collect(Collectors.toMap(AllCoinEntity::getCoin, AllCoinEntity::getId));
得到的map即是以coin为key,主键id为value的map对象

三、排序

  • achievementList:为成绩集合
  • Achievement:成绩实体
  • score分数为BigDecimal类型
List<Achievement> achievement1 = achievementList.stream().sorted(Comparator.comparing(Achievement::getScore)).collect(Collectors.toList());//根据分数排序 -- 顺序

List<Achievement> achievement2 = achievementList.stream().sorted(Comparator.comparing(Achievement::getScore).reversed()).collect(Collectors.toList());//根据分数排序 -- 倒序

注意:如果getScore方法里面有空值,需提前判断并设置为"",不然会包空指针异常


可参考:

  • https://cloud.tencent.com/developer/article/1187831 Stream(上)
  • https://cloud.tencent.com/developer/article/1187833 Stream(下)
  • http://www.runoob.com/java/java8-streams.html 菜鸟教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章