簡體   English   中英

在地圖中加入List <String>

[英]Joining a List<String> inside a map

我正在嘗試將Map<String, List<String>>轉換為Map<String, String> ,其中每個鍵的值是通過連接上一個映射中List中的所有值而構建的聯合字符串,例如:

A -> ["foo", "bar", "baz"]
B -> ["one", "two", "three"]

應轉換為

A -> "foo|bar|baz"
B -> "one|two|three"

使用Java 8 Streams API執行此操作的慣用方法是什么?

只需使用String.join ,無需創建嵌套流:

Map<String, String> result = map.entrySet()
                            .stream()
                            .collect(toMap(
                                e -> e.getKey(), 
                                e -> String.join("|", e.getValue())));

您可以使用Collectors.joining(delimiter)執行此任務。

Map<String, String> result = map.entrySet()
                                .stream()
                                .collect(toMap(
                                    Map.Entry::getKey, 
                                    e -> e.getValue().stream().collect(joining("|")))
                                );

在此代碼中,地圖中的每個條目都會收集到新地圖中,其中:

  • 鑰匙保持不變
  • 通過將所有元素連接在一起,將值(列表)收集到String

谷歌番石榴有一個很好的幫助方法:

com.google.common.collect.Maps.transformValues(map, x -> x.stream().collect(joining("|")));

使用純java,這將工作:

map.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().stream().collect(joining("|"))));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM