Jin Kwon Jin Kwon - 1 year ago 81
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

q1 a, b
q2 c, 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] ? '?' : '&')

Answer Source

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 =
       .flatMap(e -> e.getValue().stream().map(v -> e.getKey() + '=' + v))

Input :

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

Output :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download