【java 基础】使用Java8 Stream简化列表数据过滤

1 篇文章 0 订阅

下半年跳槽换了一份工作,在cetc10的工作环境上网不太方便,到现在blog一篇都没更新又懈怠了,深刻检讨啊 - -!

上个月项目遇到需要对后端DAO返回的List数据按业务需要进行数据过滤,保留符合条件的条目。

很直观的想法就是,foreach遍历list,可能需要嵌套循环,这种代码看起来有点low

java 8的Stream流,提供有方便的map、filter方法,可以简化编码逻辑,具体如下:

List<PlaneInfo> planeInfos = new ArrayList<>();

        planeInfos.add(new PlaneInfo(1L,null,0,null));

        planeInfos.add(new PlaneInfo(2L,4L,0,null));

        planeInfos.add(new PlaneInfo(3L,4L, 1,Arrays.asList("#3进入海峡")));

        planeInfos.add(new PlaneInfo(4L,4L,0,null));

        planeInfos.add(new PlaneInfo(5L,4L, 1,Arrays.asList("#5进入海峡")));

        planeInfos.add(new PlaneInfo(6L,6L, 0,Arrays.asList("#6 no ytq")));


        List<PlaneInfo> noytqList = new ArrayList<>();

        noytqList = (planeInfos.stream().filter(o->o.getHpid() != null && o.isYtq.compareTo(0) == 0)
                .collect(Collectors.toList())); //使用filter过滤

        List<PlaneInfo> ytqList = planeInfos.stream().filter(o->o.getHpid() != null && o.isYtq.compareTo(1) == 0)
                .collect(Collectors.toList());


        noytqList.forEach(o-> {
            if(ytqList.stream().noneMatch(y-> y.getHpid().compareTo(o.getHpid()) == 0 )) //noneMatch匹配
                ytqList.add(o);
        });

 

关键是使用到了filter和noneMatch进行过滤和匹配,代码看起来简洁很多。

todo:Steam的性能如何,还需要进一步研究。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值