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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/errizh/article/details/84696581

下半年跳槽换了一份工作,在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的性能如何,还需要进一步研究。

猜你喜欢

转载自blog.csdn.net/errizh/article/details/84696581