有点复杂,但它可以工作:
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转换为所需输出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;}));