ポール・バク:
私のようなマップの構造のマップを持っています:
Map<Center, Map<Product, Value>> given
そして私が取得したいです
Map<Product, Map<Center, Value>> result
私は、Javaのストリームを使用しました
Map<Product, Map<Center, Value>> result = given.entrySet().stream()
.flatMap(entry -> entry.getValue()
.entrySet().stream()
.map(e -> Triple(entry.getKey(), e.getKey(), e.getValue())))
.collect(Collectors.groupingBy(Triple::getProduct,
Collectors.toMap(Triple::getCenter, Triple::getValue)));
どこTriple
単純な値のクラスがあります。私の質問は、機能の追加クラスのように使用しなくても、それを行うことが可能である場合であるTriple
かなどをTable
グアバから?
Ousmane D .:
あなたは、ストリームのアプローチを続行したい場合は残念ながら、それはだ避けられない中間オブジェクト、すなわち、いくつかのタイプを作成するためにTriple
、またはAbstractMap.SimpleEntry
または該当する他のタイプを。
あなたは、基本的にC#の匿名型のようなものを探しているあなただけにマップすることができ、すなわち、
new { k1 = entry.getKey(), k2 = e.getKey(), k3 = e.getValue()) }
その後、すぐにではそれらのアクセスgroupingBy
およびtoMap
位相を。
Javaは何か持っている類似したが、かなりではない、あなたが行うことができます。すなわち:
Map<Product, Map<Center, Value>> result =
given.entrySet()
.stream()
.flatMap(entry -> entry.getValue()
.entrySet().stream()
.map(e -> new Object() {
Center c = entry.getKey();
Product p = e.getKey();
Value v = e.getValue();
}))
.collect(Collectors.groupingBy(o -> o.p, Collectors.toMap(o -> o.c, o -> o.v)));
クレジットは@shmoselに行きます。
ここでの唯一の利点は、カスタムクラスを事前定義する必要はありませんされています。