Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stream a Map<String, List<Object>> into a Stream<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[] flag = new boolean[1];
    params.forEach((n, vs) -> {
        vs.forEach(v -> {
            builder.append(flag[0] ? '&' : '?')
                    .append(n)
                    .append('=')
                    .append(v);
            if (!flag[0]) {
                flag[0] = true;
            }
        });
    });
}
like image 506
Jin Kwon Avatar asked Aug 07 '16 10:08

Jin Kwon


People also ask

How to collect a stream of list into map in Java?

Learn various ways of Collecting a Stream of List into Map using Java Streams API. Using Collectors.toMap and Collectors.groupingBy with example. Let’s consider, you have a User class and a List of the users which you want to convert to Map.

What are the examples of stream map?

Example 1 : Stream map () function with operation of number * 3 on each element of stream. Example 2 : Stream map () function with operation of converting lowercase to uppercase.

How to convert a stream to a map in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. In this article, the methods to convert a stream into a map is discussed. Method 1: Using Collectors.toMap () Function

How to convert a stream to a map using collectors?

The Collectors.toMap () method takes two parameters as the input: KeyMapper: This function is used for extracting keys of the Map from stream value. ValueMapper: This function used for extracting the values of the map for the given key. The following are the examples of the toMap function to convert the given stream into a map:


2 Answers

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
like image 175
Eran Avatar answered Oct 30 '22 11:10

Eran


If you have Guava, you might want to consider using a ListMultimap<String, Object> instead of Map<String, List<Object>>, and create your string like so:

String query = Joiner.on("&").withKeyValueSeparator("=").join(map.entries());
like image 23
shmosel Avatar answered Oct 30 '22 11:10

shmosel