MapString MapString StatisticsResultDTO 使用stream转为MapString StatisticsResultDTO
可以使用流操作来将 Map<String, Map<String, StatisticsResultDTO>> 转换为 Map<String, StatisticsResultDTO>。可以按照以下步骤进行转换:
- 获取外层 Map 的键集合,并创建一个空的结果 Map。
- 对于每个外层键,获取对应的内层 Map。
- 使用流操作对内层 Map 的值集合进行合并,将每个 StatisticsResultDTO 对象的 name 作为键,对象本身作为值。
- 将内层 Map 中的值合并为一个 StatisticsResultDTO 对象。
- 将外层键和合并后的 StatisticsResultDTO 对象作为键值对放入结果 Map 中。
下面是一个示例代码:
Map<String, Map<String, StatisticsResultDTO>> inputMap = ...;
Map<String, StatisticsResultDTO> resultMap = inputMap.keySet().stream()
.collect(Collectors.toMap(
outerKey -> outerKey,
outerKey -> inputMap.get(outerKey).values().stream()
.reduce(new StatisticsResultDTO(), (dto1, dto2) -> {
dto1.setName(dto2.getName());
dto1.setCount(dto1.getCount() + dto2.getCount());
dto1.setAverage(dto1.getAverage() + dto2.getAverage());
return dto1;
})
));
在上面的代码中,我们使用了 collect 方法来收集流的结果,并使用 Collectors.toMap 方法将外层键和合并后的 StatisticsResultDTO 对象放入结果 Map 中。内层 Map 的合并操作使用了 reduce 方法,将每个 StatisticsResultDTO 对象的 count 和 average 进行累加,并将最后一个对象的 name 设置为合并后的对象的 name。
原文地址: https://www.cveoy.top/t/topic/i7Td 著作权归作者所有。请勿转载和采集!