将两个List根据某些相同属性进行合并

1.使用strean

        List<Apple> details = new ArrayList<>();
        List<Apple> counts = new ArrayList<>();
        .......
        List<Apple> results = details.stream().map(m1 -> {
                    counts.stream().filter(m2 -> Objects.equals(m1.getAppleId(), m2.getAppleId())).forEach(m2 -> {
                        m1.setAppleCount(m2.getAppleCount());
                    });
                    return m1;
                }).collect(Collectors.toList());


2.使用parallelStream

        List<Apple> details = new ArrayList<>();
        List<Apple> counts = new ArrayList<>();
        .......
        List<Apple> results = details.parallelStream().map(m1 -> {
                    counts.parallelStream().filter(m2 -> Objects.equals(m1.getAppleId(), m2.getAppleId())).forEach(m2 -> {
                        m1.setAppleCount(m2.getAppleCount());
                    });
                    return m1;
                }).collect(Collectors.toList());


3.使用map

        List<Apple> details = new ArrayList<>();
        List<Apple> counts = new ArrayList<>();
        ........
        Map<String, Apple> map = new HashMap<>();
        for(Apple detail : details) {
            map.put(detail.getAppleId(), detail);
        }
        List<Apple> results2 = new ArrayList<>();
        for(Apple count : counts){
            Apple detail = map.get(count.getAppleId());
            if (Objects.isNull(detail)) continue;
            detail.setAppleCount(count.getAppleCount());
            results2.add(detail);
        }

效率对比:3 > 2 > 1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容