如何在Java 8中将Map <string,list <string =“” >>转换为Map <string,string =“”>

时间:2018-11-17 22:23:27

标签: java java-8 java-stream

我有一个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作为中间步骤?

1 个答案:

答案 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)));