Java8: converting a map <String, List <String> to Map <String, String> by concatenating values

I have Map<String, List<String>>one that I would like to convert to Map<String, String>, the result values ​​would be String.join(" - ", values)for the first values ​​of the map.

I know how to do 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 new HashMap<>()and directly perform the input conversion.
I suspect that collect(Collectors.groupingBy( something ) ), but I can’t understand how.
I want to look like this:

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

How should I do it?

+4
source share
1 answer

No need to group. Just write the entries in a new one Map:

Map<String, String> map = 
    attributes.entrySet()
              .stream()
              .collect(Collectors.toMap(Map.Entry::getKey,
                                        e-> String.join(" - ", e.getValue())));
+5
source

Source: https://habr.com/ru/post/1672906/


All Articles