亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用流將 Map<A, Map<B, C>> 轉換為 Map<B, Map<A, C>>

使用流將 Map<A, Map<B, C>> 轉換為 Map<B, Map<A, C>>

喵喔喔 2022-01-19 16:54:11
我有地圖的結構圖,例如: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番石榴)的情況下實現它的功能?
查看完整描述

2 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

沒有流,有些事情會更容易完成:


Map<Product, Map<Center, Value>> result = new HashMap<>();

given.forEach((c, pv) -> pv.forEach((p, v) ->

        result.computeIfAbsent(p, k -> new HashMap<>()).put(c, v)));


查看完整回答
反對 回復 2022-01-19
?
DIEA

TA貢獻1820條經驗 獲得超3個贊

不幸的是,如果您想繼續使用流方法,則不可避免地要創建某種類型的中間對象Triple,即 ie 或AbstractMap.SimpleEntry任何其他適用的類型。


您實際上是在尋找類似 C# 的匿名類型的東西,即您可以映射到


new { k1 = entry.getKey(), k2 = e.getKey(), k3 = e.getValue()) }

然后立即訪問groupingByandtoMap階段的那些。


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。


唯一的好處是您不需要預定義自定義類。


查看完整回答
反對 回復 2022-01-19
  • 2 回答
  • 0 關注
  • 244 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號