Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - map to comma separated pairs in brackets

Tags:

java-8

What is the best way in Java 8 to get from

Map<Integer, Integer>

to a String like:

[k1,v1],[k2,v2],[k3,v3]...

I am looking at something like this, but I don't know how to "return" or "map" the StringBuilder:

map.forEach( (k,v) -> s.append("[").append(k).append(",").append(v).append("]") )
                    .collect(Collectors.joining(", "));

In any case, I believe StringBuilder is not suitable for multithreading in case of future paralelism.

Note that I could iterate over the Map and create all the structure in an old fashion, but I would like to see how it could be done with some new Java8 features.

I think some toString() by chance already returns the map values in brackets, which could be convenient, although it is not really a good idea to rely on this.

like image 393
user1156544 Avatar asked Mar 06 '17 17:03

user1156544


1 Answers

map.entrySet()
   .stream()
   .map(e -> "[" + e.getKey() + "," + e.getValue() + "]")
   .collect(Collectors.joining(","));
like image 171
JB Nizet Avatar answered Dec 11 '22 17:12

JB Nizet