gpt4 book ai didi

java - map 到 map

转载 作者:搜寻专家 更新时间:2023-10-31 19:51:31 25 4
gpt4 key购买 nike

我想切换 map 的键和其中的 map :

Map<X, Map<Y, Z> -> Map<Y, Map<X, Z>

我试过使用流,但无法创建内部映射或如何分别从原始内部映射访问键和值。

//到目前为止我已经尝试过:

originalMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));

最佳答案

有点复杂,但它有效:

Map<Y,Map<X,Z>> out =
originalMap.entrySet()
.stream()
.flatMap(e -> e.getValue()
.entrySet()
.stream()
.map(e2 -> {
Map<X,Z> m = new HashMap<>();
m.put(e.getKey(),e2.getValue());
return new SimpleEntry<>(e2.getKey(),m);}))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(v1,v2)->{v1.putAll(v2);return v1;}));

基本上,它将原始 Map 条目的 Stream 转换为所需输出 的平面条目的 Stream Map(其中每个内部 Map 只有一个 Entry),并使用带有合并功能的 toMap 收集器来合并内部 Map 对应于相同的外部键。

例如,使用以下输入 Map 运行此代码:

Map<String,Map<Integer,Double>> originalMap = new HashMap<>();
Map<Integer,Double> inner1 = new HashMap<>();
Map<Integer,Double> inner2 = new HashMap<>();
Map<Integer,Double> inner3 = new HashMap<>();
originalMap.put("aa",inner1);
originalMap.put("bb",inner2);
originalMap.put("cc",inner3);
inner1.put(10,10.0);
inner1.put(20,20.0);
inner1.put(30,30.0);
inner2.put(10,40.0);
inner2.put(20,50.0);
inner2.put(30,60.0);
inner3.put(10,70.0);
inner3.put(20,80.0);
inner3.put(30,90.0);

Map<Integer,Map<String,Double>> out =
originalMap.entrySet()
.stream()
.flatMap(e -> e.getValue()
.entrySet()
.stream()
.map(e2 -> {
Map<String,Double> m = new HashMap<>();
m.put(e.getKey(),e2.getValue());
return new SimpleEntry<>(e2.getKey(),m);}))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(v1,v2)->{v1.putAll(v2);return v1;}));
System.out.println (out);

将输出:

{20={aa=20.0, bb=50.0, cc=80.0}, 10={aa=10.0, bb=40.0, cc=70.0}, 30={aa=30.0, bb=60.0, cc=90.0}}

编辑:

如果您使用的是 Java 9 或更高版本,您可以使用 Map.of 来简化代码:

Map<Y,Map<X,Z>> out =
originalMap.entrySet()
.stream()
.flatMap(e -> e.getValue()
.entrySet()
.stream()
.map(e2 -> new SimpleEntry<>(e2.getKey(),Map.of(e.getKey(),e2.getValue()))))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(v1,v2)->{v1.putAll(v2);return v1;}));

关于java - map <X, map <Y, Z> 到 map <Y, map <X, Z>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57052934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com