Reputation: 86847
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.
Upvotes: 2
Views: 859
Reputation: 40078
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());
Upvotes: 1
Reputation: 16224
What about joining the values with streams?
public static void main(String[] args) {
Map<String, List<String>> headers = new HashMap<>();
headers.put("KEY1", Arrays.asList("v1,v2,v3"));
headers.put("KEY2", Arrays.asList("v1,v2,v3"));
List<String> res = headers.entrySet().stream().map(stringListEntry ->
stringListEntry.getKey() + "=" +
String.join(", ", stringListEntry.getValue())
).collect(Collectors.toList());
System.out.println(res);
}
result
[KEY2=v1,v2,v3, KEY1=v1,v2,v3]
Upvotes: 0
Reputation: 3138
Do the same thing with the values
:
[...]
.map(e -> e.getKey() + "=" + e.getValue().stream().collect(Collectors.joining(", "))
[...]
Edit: as @Eugene said, the parameter is a Map.Entry (e)
and not (key,values)
Upvotes: 1