Gui13
Gui13

Reputation: 13541

Java8: Transform Map<String,List<String>> into Map<String,String> by joining the values

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?

Upvotes: 4

Views: 406

Answers (1)

Eran
Eran

Reputation: 393781

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())));

Upvotes: 5

Related Questions