我有一个map
key= ["a1", "a2", "a3"]
value = [["a1.value1", "a1.value2"],["a2.value1", "a2.value2"]]
生成的地图应类似于
key = ["a1", "a2", "a3"]
value = ["a1.value1, a1.value2", "a2.value1, a2.value2"]
我们如何使用Collectors.joining
作为中间步骤?
答案 0 :(得分:7)
我们如何使用Collectors.join作为中间步骤?
您的意思是,在收集阶段...
是的,您可以:
Map<String, String> result =
source.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey,
e -> e.getValue().stream().collect(joining(", "))));
但是,最好使用String.join
:
Map<String, String> result =
source.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> String.join(", ", e.getValue())));
或无流变体:
Map<String, String> resultSet = new HashMap<>();
source.forEach((k, v) -> resultSet.put(k, String.join(",", v)));