Java Stream: 如何将 Map<String, Map<String, Map<String, StatisticsResultDTO>>> 转换为 Map<String, Map<String, StatisticsResultDTO>>
您可以使用flatMap方法来将integrityLevelSubtotal的中间Map转换为一个Stream,然后再使用collect方法将其转换为目标Map。
以下是一个示例代码:
Map<String, Map<String, StatisticsResultDTO>> result = integrityLevelSubtotal.entrySet().stream()
.flatMap(entry -> entry.getValue().entrySet().stream()
.map(innerEntry -> new AbstractMap.SimpleEntry<>(entry.getKey(), new AbstractMap.SimpleEntry<>(innerEntry.getKey(), innerEntry.getValue())))
)
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> {
Map<String, StatisticsResultDTO> innerMap = new HashMap<>();
innerMap.put(entry.getValue().getKey(), entry.getValue().getValue());
return innerMap;
},
(existing, replacement) -> {
existing.putAll(replacement);
return existing;
}
));
在这个示例中,我们使用flatMap方法将integrityLevelSubtotal的中间Map转换为一个Stream,并将每个键值对转换为一个新的AbstractMap.SimpleEntry对象。然后使用collect方法将这些SimpleEntry对象转换为目标Map。
请注意,为了保持中间Map的键值对结构,我们在collect方法中使用了一个合并函数(existing, replacement) -> {...},以便将相同键的值合并到同一个内部Map中。
最后,您将得到一个不包含中间Map键的目标Map<String, Map<String, StatisticsResultDTO>>。
原文地址: https://www.cveoy.top/t/topic/lTpS 著作权归作者所有。请勿转载和采集!