Jin Kwon Jin Kwon - 3 months ago 13
Java Question

How can I stream a Map<String, List<Object>> into a <Entry<String, Object>>?

I have a

Map<String, List<Object>>
.

How can I make it into a Stream of
Entry<String, Object>
so that I can construct a concatenated query
String
?

q1 a, b
q2 c, d


into

q1=a&q1=b&q2=c&q2=d


I'm, currently, doing this.

if (params != null && !params.isEmpty()) {
final boolean[] first = new boolean[1];
params.forEach((n, vs) -> {
vs.forEach(v -> {
builder.append(first[0] ? '?' : '&')
.append(n)
.append('=')
.append(v);
});
});
}

Answer

Well, you don't have to produce a Entry<String, Object>. You can use flatMap to obtain the key=value Strings and directly construct the query String using Collectors.joining:

String query =
    map.entrySet()
       .stream()
       .flatMap(e -> e.getValue().stream().map(v -> e.getKey() + '=' + v))
       .collect(Collectors.joining("&"));

Input :

{q1=[a, b], q2=[c, d]}

Output :

q1=a&q1=b&q2=c&q2=d
Comments