使用streams将Map<String, Map<String, Integer>>转换为Map<String, Integer>的方法如下:
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<String, Map<String, Integer>> inputMap = new HashMap<>();
// 添加示例数据
Map<String, Integer> innerMap1 = new HashMap<>();
innerMap1.put("A", 1);
innerMap1.put("B", 2);
inputMap.put("Key1", innerMap1);
Map<String, Integer> innerMap2 = new HashMap<>();
innerMap2.put("C", 3);
innerMap2.put("D", 4);
inputMap.put("Key2", innerMap2);
// 使用streams将Map<String, Map<String, Integer>>转换为Map<String, Integer>
Map<String, Integer> outputMap = inputMap.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().values().stream()
.reduce(0, Integer::sum)));
// 打印转换后的结果
outputMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
输出结果为:
Key1: 3
Key2: 7
在上述代码中,我们首先创建了一个示例的Map<String, Map<String, Integer>>
,其中包含了两个外层的键值对,每个键对应一个内层的Map<String, Integer>
。然后,我们使用streams对外层的Map
进行操作,通过Collectors.toMap
方法将外层的键作为新的Map
的键,内层的Map
的值进行求和后作为新的Map
的值。最后,我们通过遍历新的Map
打印出转换后的结果。
这种转换方法适用于需要将嵌套的Map
转换为扁平化的Map
的场景,例如统计每个外层键对应的内层值的总和。在腾讯云的产品中,可以使用云数据库 TencentDB 来存储和管理这样的数据,具体可以参考腾讯云数据库 TencentDB 的产品介绍:https://cloud.tencent.com/product/cdb。
领取专属 10元无门槛券
手把手带您无忧上云