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.
map.entrySet()
.stream()
.map(e -> "[" + e.getKey() + "," + e.getValue() + "]")
.collect(Collectors.joining(","));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With