4

I have a Map<String, List<String>> that I would like to transform into a Map<String, String>, the values of the result would be a String.join(" - ", values) of the first map's values.

I know how to do it like this:

public Map<String,String> flatten( Map<String, List<String>> attributes) {
      Map<String, String> map = new HashMap<>();
      attributes.forEach((k,v) -> map.put( k, String.join(" - ", v)));
      return map;
}

But I would like to get rid of the new HashMap<>() and directly do the transformation on the input.
I suspect a collect(Collectors.groupingBy( something ) ) but I can't figure out how.
What I want looks like this:

public Map<String,String> flatten( Map<String, List<String>> attributes) {
    return attributes.entrySet().stream().<something>;
}

How would I do that?

1 Answer 1

5

No need to group by. Just collect the entries into a new Map :

Map<String, String> map = 
    attributes.entrySet()
              .stream()
              .collect(Collectors.toMap(Map.Entry::getKey,
                                        e-> String.join(" - ", e.getValue())));
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.