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

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

如何使用 Java 8 Streams 將列表中的對象與地圖中的數據與條件進行匹配并保存到另一個地圖

如何使用 Java 8 Streams 將列表中的對象與地圖中的數據與條件進行匹配并保存到另一個地圖

SMILET 2023-08-16 17:41:17
尋找解決方案,如果對象字段以地圖值開頭并保存到另一個地圖,如何將列表中的對象與地圖中的數據與條件進行匹配我有帶有一些數據的地圖Map<String, String> dataMap = new HashMap()    dataMap.put("d1", "DATA1")    dataMap.put("d2", "DATA2")    dataMap.put("d3", "DATA3")和 DataElement 對象的列表    List<DataElement> elements = new ArrayList()elements.add(new DataElement("TEXT1"))elements.add(new DataElement("TEXT2"))elements.add(new DataElement("DATA1_text1"))elements.add(new DataElement("DATA2_text2"))class DataElement {            public field;        public DataElement(String text){            this.field = text        }        public getField(){            return this.field        }    }我正在嘗試獲取新的 Map,其中鍵是第一個映射中的值,值是列表中的對象(字段),條件是如果對象字段以映射值開頭:結果應該是:[d1=DATA1_text1, d2=DATA2_text2]  我的代碼:    Map<String, String> collect2 = dataMap.entrySet().stream()            .filter({ map -> elements.stream()                                .anyMatch({ el -> el.getField().startsWith(map.getValue()) })})            .collect(Collectors.toMap(KEY, VALUE))
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

希望我的問題是正確的:


Map<String, String> collect2 = 

    dataMap.entrySet()

          .stream()

          .map(e -> elements.stream()

                            // this will search for the first element of the List matching

                            // the value of the current Entry, if exists

                            .filter(el -> el.getField().startsWith(e.getValue()))

                            .findFirst()

                            // this will create a new Entry having the original key and the

                            // value obtained from the List

                            .map(el -> new SimpleEntry<>(e.getKey(),el.getField()))

                            // if findFirst found nothing, map to a null element

                            .orElse(null))

          .filter(Objects::nonNull) // filter out all the nulls

          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

您正在處理 input 的條目Map,并僅保留具有與 的元素匹配的值的條目List(通過filter(),盡管有一些語法錯誤),但您需要將map輸入條目轉換為包含所需新值的新條目。


上面的代碼產生Map


{d1=DATA1_text1, d2=DATA2_text2}

對于給定的輸入。


查看完整回答
反對 回復 2023-08-16
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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