![](/img/trans.png)
[英]Java8: Transform Map<String,List<String>> into Map<String,String> by joining the values
[英]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.