stream 分组(group)和map的值映射mapping

@Data
public class MiddleFloorDto {
    private Long middleId;
    private Long floorId;
    private Long landingpageId;
}

  

public class Main {
    public static void main(String[] args) {
        ArrayList<MiddleFloorDto> list = new ArrayList<>();
          MiddleFloorDto dto1 = new MiddleFloorDto();
        dto1.setFloorId(1l);
        dto1.setLandingpageId(1l);
          MiddleFloorDto dto2 = new MiddleFloorDto();
        dto2.setFloorId(12l);
        dto2.setLandingpageId(2l);
          MiddleFloorDto dto3 = new MiddleFloorDto();
        dto3.setFloorId(8l);
        dto3.setLandingpageId(2l);
          MiddleFloorDto dto4 = new MiddleFloorDto();
          dto4.setMiddleId(2l);
        dto4.setLandingpageId(3l);
           MiddleFloorDto dto5 = new MiddleFloorDto();
           dto5.setFloorId(2l);
        dto5.setLandingpageId(4l);
          MiddleFloorDto dto6 = new MiddleFloorDto();
          dto6.setFloorId(4l);
        dto6.setLandingpageId(2l);
          MiddleFloorDto dto7 = new MiddleFloorDto();
          dto7.setFloorId(6l);
        dto7.setLandingpageId(2l);
        list.add(dto7);
        list.add(dto6);
        list.add(dto5);
        list.add(dto4);
        list.add(dto3);
        list.add(dto2);
        list.add(dto1);
         Map<Long, List<MiddleFloorDto>> collect = list.stream().collect(Collectors.groupingBy(MiddleFloorDto::getLandingpageId));
         System.out.println(collect.get(1l));
        System.out.println(collect.get(2l));
        System.out.println(collect.get(3l));
        System.out.println(collect.get(4l));
        System.out.println(collect.get(5l));
        System.out.println(collect.get(6l));
     }

  

list.stream() .collect(Collectors.groupingBy(MiddleFloorDto::getLandingpageId, Collectors.mapping(MiddleFloorDto::getFloorId, Collectors.toList())));
 

/* [MiddleFloorDto{middleId=null, floorId=1, landingpageId=1}] [MiddleFloorDto{middleId=null, floorId=6, landingpageId=2}, MiddleFloorDto{middleId=null, floorId=4, landingpageId=2}, MiddleFloorDto{middleId=null, floorId=8, landingpageId=2}, MiddleFloorDto{middleId=null, floorId=12, landingpageId=2}] [MiddleFloorDto{middleId=2, floorId=null, landingpageId=3}] [MiddleFloorDto{middleId=null, floorId=2, landingpageId=4}] null null*/
测试结果符合预期。
posted @ 2022-01-08 22:51  三号小玩家  阅读(1092)  评论(0编辑  收藏  举报
Title
三号小玩家的 Mail: 17612457115@163.com, 联系QQ: 1359720840 微信: QQ1359720840