アニア:
私はその中のマップとマップのキーを切り替えたいです:
Map<X, Map<Y, Z> -> Map<Y, Map<X, Z>
私は、ストリームを使用しようとしましたが、別にオリジナルの内部マップからアクセスキーと値に内部マップまたはどのように作成することはできません。
//これまでのところ私が試してみました:
originalMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
彼らは次のとおりでした:
Aは、複雑なビットが、それは動作します:
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;}));
基本的には、変換Stream
元のMap
内のエントリをStream
、所望の出力の平坦エントリMap
(各々内にMap
1つだけ有しているEntry
)、及び使用toMap
内側マージするマージ機能をコレクタMap
Sをその同じ外側のキーに対応。
例えば、以下の入力地図でこのコードを実行しています:
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}}
EDIT:
あなたが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;}));