5

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 ?

2
  • Welcome to Stack Overflow! Please take the tour and visit our help center to learn what kinds of questions are appropriate for this site. If you can edit your question to fit the requirements of this site, please do so. Commented Nov 17, 2018 at 22:24
  • 3
    Not sure I understand your question... are you trying to map multiple values to the same key in a Map, i.e. have multiple Map entries per a specific key? In a Java Map, the keys are a set, meaning no single key value can repeat. Commented Nov 17, 2018 at 22:27

1 Answer 1

7

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)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.