How to join a MultiValueMap with Stream api?

membersound :

I have a org.springframework.util.MultiValueMap extends Map<String, List<String>> hierarchy. I want to collect all values just as a concatenated csv string:

        HttpHeaders headers;
        headers.entrySet().stream()
                .map((key, values) -> key + "=" + values) //TODO incompatible parameter types
                .collect(Collectors.joining(", "));

Question: how can I join the (key, values) pair correctly? As I get the error above.

Deadpool :

By using Collectors.joining

List<String> result = headers.entrySet().stream()
            .map(e -> e.getKey() + " = " + e.getValue().stream().collect(Collectors.joining(",")))
            .collect(Collectors.toList());

    System.out.println(result);    //[KEY2 = v1,v2,v3, KEY1 = v1,v2,v3]

As @Eugene suggested you can also use String.join

 List<String> result = headers.entrySet().stream()
            .map(e -> e.getKey() + " = " + String.join(",",e.getValue()))
            .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=131663&siteId=1