stackaccount
stackaccount

Reputation: 79

How to Convert a Map<String, List<String>> to Map<String, String> in java 8

I have a map like

key= ["a1", "a2", "a3"] 
value = [["a1.value1", "a1.value2"],["a2.value1", "a2.value2"]]

the resulting Map should be like

key = ["a1", "a2", "a3"]
value = ["a1.value1, a1.value2", "a2.value1, a2.value2"]

How can we use Collectors.joining as an intermediate step ?

Upvotes: 5

Views: 1546

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56499

How can we use Collectors.joining as an intermediate step ?

You mean, in the collecting phase...

Yes, you can:

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

but, better to use String.join:

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

or none stream variant:

Map<String, String> resultSet = new HashMap<>();
source.forEach((k, v) -> resultSet.put(k, String.join(",", v)));

Upvotes: 7

Related Questions