Java-8 – Java 8 – maps to comma separated pairs in parentheses
•
Java
What is the best method in Java 8?
Map<Integer,Integer>
Like a string:
[k1,v1],[k2,v2],[k3,v3]...
I'm looking at something like this, but I don't know how to "return" or "map" 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 parallel multithreading in the future
Note that I can iterate over the map and create all the structures in the old way, but I want to see how to do it with some new Java 8 features
I think some toString () occasionally returns map values in parentheses, which may be convenient, although it's not a good idea to rely on this
Solution
map.entrySet()
map.entrySet() .stream() .map(e -> "[" + e.getKey() + "," + e.getValue() + "]") .collect(Collectors.joining(","));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码