java8 Stream 自定义分组

    技术2023-10-17  78

    根据某一个字段分组,返回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()));

     

    Processed: 0.011, SQL: 9