地図<A、地図<B、C >>地図に<B、地図<A、C >>使用してストリームに変換

ポール・バク:

私のようなマップの構造のマップを持っています:

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に行きます。

ここでの唯一の利点は、カスタムクラスを事前定義する必要はありませんされています。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=196952&siteId=1