java8 Stream 自定义分组

  1. 根据某一个字段分组,返回map的value值进行更换。在收集器mapping中进行新对象数据的组装
List<CustomField> customFields = this.getAllCostomFromCache(tenantId);
Map<Long, List<RegisterFieldOptionVo>> customFieldMap = customFields.stream()
                .collect(Collectors.groupingBy(CustomField::getFieldId, Collectors.mapping(v -> {
                    RegisterFieldOptionVo vo = new RegisterFieldOptionVo();
                    vo.setId(v.getOptionId());
                    vo.setValue(v.getOptionValue());
                    vo.setFieldId(v.getFieldId());
                    return vo;
                }, Collectors.toList())));

    2.分组后对value值(list)进行排序。先在流中对原始集合中的对象进行排序,分组就适用了

List<CustomField> customFields = this.getAllCostomFromCache(tenantId);
Map<Long, List<RegisterFieldOptionVo>> customFieldMap = customFields.stream()
                .sorted(Comparator.comparingLong(CustomField::getOptionId))
                .collect(Collectors.groupingBy(CustomField::getFieldId, Collectors.mapping(v -> {
                    RegisterFieldOptionVo vo = new RegisterFieldOptionVo();
                    vo.setId(v.getOptionId());
                    vo.setValue(v.getOptionValue());
                    vo.setFieldId(v.getFieldId());
                    return vo;
                }, Collectors.toList())));

    3.分组后返回的value改为map。不使用收集器,直接使用Collectors.toMap进行收集数据

List<CustomField> optionsListByValues =registerFieldAPIService.getOptionsListByValues(req);
Map<Long, Map<String, Long>> optionsMap = optionsListByValues.stream()
                        .collect(Collectors.groupingBy(CustomField::getFieldId, Collectors.toMap(CustomField::getOptionValue, v -> v.getOptionId())));

4.分组后返回的value为每个分组中的某个字段拼接值

List<HouseConfig> houseConfigs = Lists.newArrayList();        
Map<Long, String> stringMap = houseConfigs.stream()
                .collect(Collectors.groupingBy(HouseConfig::getId, Collectors.mapping(HouseConfig::getCode, Collectors.joining(",")));

5.分组后统计个数

Map<String, Long> stateMap = houseList.stream().collect(Collectors.groupingBy(House::getState, Collectors.counting()));

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值