练涛

java8 Stream()等特性的实操,即用即翻

突然觉得,把常用的操作记录到一个本子,用到就查查,那该多美妙,现在这个本子就选这吧 --2020-9-8

  • Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)
 //获取isdelete为2的数据,并返回新的list
        List<ArchivesVo> collect = ArchivesVoList.stream().filter(s -> s.getIsdelete() == 2).collect(Collectors.toList());
  • stream().map()将多个id批量获取实体对象
//ids是一个id集合: List<Long> ids
List<Cost> CostList = ids.stream().map(l ->costService.getById(l)).collect(Collectors.toList());
  • stream().map()批量修改所有item的某个属性值
//把所有的cost的isdelete改为1
 List<Cost> collect = CostList.stream().map(cost -> cost.setIsdelete(1)).collect(Collectors.toList());
//于是批量更新可以用:
 boolean b = costService.updateBatchById(collect);
  • stream().max()从list从筛选日期最大值的对象
      //获取日期最大值的对象
        Gg gg = list.stream().max(Comparator.comparing(Gg::getGgDate)).get();   

  • 使用map()把字符串按照某个字符切割,并存成hashmap.

Map<String, String> collect = replaced.stream().map(m -> m.split("=")).collect(Collectors.toMap(a -> a[0].trim(), a -> a.length > 1 ? a[1].trim() : " "));

  • 使用filter, noneMatch、anyMatch 遍历集合匹配。 相当于双重for循环
        //假设有个list里面有很多值
        channelIdByPhone.add("1");
        channelIdByPhone.add("2");
        //获取 uid not in 集合(channelIdByPhone)的项,返回一个新的list 
        List<ProductInfoEntity> zk_collect = collect.stream()
//                .filter(o -> !channelIdByPhone.stream().anyMatch(str -> str.equals(o.getUid().toString())))
                .filter(o -> channelIdByPhone.stream().noneMatch(str -> str.equals(o.getUid().toString())))
                .collect(Collectors.toList());

posted @ 2020-08-04 11:56  练涛  阅读(572)  评论(0编辑  收藏  举报