Java8中Stream的应用

 一、flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

 将多个列表合并成一个大的列表,可用来优化嵌套循环问题

 两层嵌套

public class Test{
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class  W{
        public String name;
        public List<M> listM;
    }
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class  M{
        public String name;
        public List<String> con;
    }


    public static void main(String[] args) {

        M  m1 = M .builder().name("m1").con(Arrays.asList("m1-1","m1-2")).build();
        M  m2 = M .builder().name("m2").con(Arrays.asList("m2-1","m2-2")).build();
        M  m3 = M .builder().name("m3").con(Arrays.asList("m3-1","m3-2")).build();
        M  m4 = M .builder().name("m4").con(Arrays.asList("m4-1","m4-2")).build();

        W w = W.builder().name("w").listM(Arrays.asList(m1,m2,m3,m4)).build();
        
        List<String> collect = w.getListM().stream().flatMap(e -> e.getCon().stream()).collect(Collectors.toList());
        System.out.println(collect);


    }

}

输出 

[m1-1, m1-2, m2-1, m2-2, m3-1, m3-2, m4-1, m4-2]

三层嵌套

public class Test {
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class  W{
        public String name;
        public List<M> listM;
    }
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class  M{
        public String name;
        public List<N> listN;
    }
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class  N{
        public String name;
        public List<String> con;
    }

    public static void main(String[] args) {

        N n1 = N.builder().name("n1").con(Arrays.asList("n1-1","n1-2")).build();
        N n2 = N.builder().name("n2").con(Arrays.asList("n2-1","n2-2")).build();
        N n3 = N.builder().name("n3").con(Arrays.asList("n3-1","n3-2")).build();
        N n4 = N.builder().name("n4").con(Arrays.asList("n4-1","n4-2")).build();
        M m1 = M.builder().name("M1").listN(Arrays.asList(n1,n2)).build();
        M m2 = M.builder().name("M3").listN(Arrays.asList(n3,n4)).build();
        W w = W.builder().name("w").listM(Arrays.asList(m1,m2)).build();

        List<String> collect = w.getListM().stream().flatMap(e -> e.getListN().stream().flatMap(x->x.getCon().stream())).collect(Collectors.toList());
        System.out.println(collect);


    }

}

 输出

[n1-1, n1-2, n2-1, n2-2, n3-1, n3-2, n4-1, n4-2]

内外层元素合成新的map(1)

Map<Long, String> idToNameMap = outList.stream()
        .flatMap(e -> e.getInnerList().stream()
                .map(p -> new AbstractMap.SimpleImmutableEntry<>(p.getId(), e.getName())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1));

内外层元素合成新的map(2)

Map<Long, Map<String, Object>> idToNameSeqMap = outList.stream()
        .flatMap(e -> e.getInnerList().stream()
                .map(p -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", e.getName());
                    map.put("sequence", e.getSequence());
                    return new AbstractMap.SimpleImmutableEntry<>(p.getId(), map);
                }))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1));

 二、peek

修改List内部的数据,peek返回类型为void,map需要一个return

            WorkManageVOS = WorkManageVOS.stream().peek(workManageVO -> {
                List<WorkProcedureVO> filteredProcedures = workManageVO.getProcedures().stream()
                        .filter(procedureVO -> procedureVO.getTS().equals(Integer.parseInt(testPipe)))
                        .collect(Collectors.toList());
                workManageVO.setProcedures(filteredProcedures);
            }).collect(Collectors.toList());

//拿外层List的属性,放到内层List中
List<workProcedureVO> updatedProcedures = workManageVOS.stream()
                    .flatMap(workManageVO -> workManageVO.getProcedures().stream().peek(procedure->{
                        procedure.setModelCode(workManageVO.getModelCode());
                        procedure.setBatchCode(workManageVO.getBatchCode());
                        procedure.setSequence(workManageVO.getSequence());
                    })).collect(Collectors.toList());

 三、Collectors.toMap

//从List中提取两个属性,组成一个新的map
Map<Integer, String> collectPipes = list.stream()
                                .collect(Collectors.toMap(EncapsulationPipeVO::getPipeCode, EncapsulationPipeVO::getPipeName));
//从list每个实例中提取一个属性值做key,实例做value组成map
Map<Integer, String> collectPipes = list.stream()
                                .collect(Collectors.toMap(EncapsulationPipeVO::getPipeCode,  Function.identity()));

四、Collectors.groupingBy

//从list每个实例中提取TM和Id,然后把id组装成List
        Map<Integer, List<Long>> collectTmMaps = workProcedureVOS.stream().collect(Collectors.groupingBy(workProcedureVO::getTM,
                Collectors.mapping(workProcedureVO::getId, Collectors.toList())));

五、

//提取List中对象属性,组成map
List<WorkManageVO> WorkManageVOS = WorkManageService.searchAllVO(build);
     // Filter the stream once and store the filtered list
    List<WorkManageVO> filteredWorkManageVOS = WorkManageVOS.stream()
            .filter(e -> e.getModelCode() != null)
            .collect(Collectors.toList());
     // modelCode -> batchCode Map
    Map<String, List<String>> batchCodeMap = filteredWorkManageVOS.stream()
            .collect(Collectors.groupingBy(WorkManageVO::getModelCode, Collectors.mapping(WorkManageVO::getBatchCode, Collectors.toList())));

//提取List中对象属性,组成map,加了去重
List<WorkManageVO> list = /* your List<WorkManageVO> instance */;
Map<String, List<String>> result = list.stream()
        .collect(Collectors.groupingBy(WorkManageVO::getModelCode, Collectors.mapping(WorkManageVO::getBatchCode, Collectors.toSet())))
        .entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArrayList<>(e.getValue())));
System.out.println(result);

///提取List中对象属性,组成map,加了去重,统计的是个数
List<WorkManageVO> list = /* your List<WorkManageVO> instance */;
Map<String, Long> result = list.stream()
        .collect(Collectors.groupingBy(WorkManageVO::getModelCode, Collectors.mapping(WorkManageVO::getBatchCode, Collectors.toSet())))
        .entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> (long) e.getValue().size()));
System.out.println(result);

 六、

//
//modelCode ->  ProjectId 
Map<String, List<Long>> projectIdMap

//ProjectId -> EncapsulationId
Map<Long, List<Long>> encapsulationIdMap

//提取所有的EncapsulationId
List<Long> encapsulationIdList = projectIdMap.getOrDefault(modelCode, Collections.emptyList())
                    .stream()
                    .flatMap(item -> encapsulationIdMap.getOrDefault(item, Collections.emptyList()).stream())
                    .collect(Collectors.toList());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值