java stream分组并更换对象,groupingBy和mapping

        List<LabelDto> labelDtos = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            labelDtos.add(LabelDto.builder().value("" + i).label("" + i).type(i % 3).build());
        }
        Map<Integer, List<LabelDto>> map = labelDtos.stream().collect(Collectors.groupingBy(LabelDto::getType));
        System.out.println("map===" + JSON.toJSONString(map));
        Map<Integer,
            List<FileDto>> map2 = labelDtos.stream()
                .collect(Collectors.groupingBy(LabelDto::getType,
                    Collectors.mapping(
                        labelDto -> FileDto.builder().name(labelDto.getLabel()).url(labelDto.getValue()).build(),
                        Collectors.toList())));

groupingBy用户分组,mapping用于对象转换,上面的根据type分组,并将LabelDto转化为FileDto返回。

mapping的用法与map类似,个人理解是返回结果的处理。

另外记几种用法:

1、list转为map

Map<String, String> stringStringMap = participantIdSet.stream().collect(Collectors.toMap(s -> s, s -> s,(oldV,newV)->oldV));

2、filter和groupingBy

Map<String, List<String>> map =
            participantIdSet.stream().filter(s -> s.startsWith("xx")).collect(Collectors.groupingBy(s -> s.substring(0, 1)));

3、.map转换

Set<LabelDto> labelDtos =
            participantIdSet.stream().map(s -> LabelDto.builder().label(s).build()).collect(Collectors.toSet());

4、map类型处理

testMap.entrySet().stream().filter(stringStringEntry -> stringStringEntry.getKey().length() == 1)
            .forEach(s -> System.out.println(s.getKey()));

Set<String> keys = testMap.entrySet().stream().map(stringStringEntry -> stringStringEntry.getKey())
            .collect(Collectors.toSet());

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值