我想为我的 HashMap<String, String> m
创建一个键值对字符串尽可能快。
我试过:
StringBuffer buf = new StringBuffer();
buf.append("[");
for (String key : m.keySet()) {
buf.append(key);
buf.append("=");
buf.append(m.get(key));
buf.append(";");
}
buf.append("]");
我尝试使用 Java8:
m.entrySet().stream()
.map(entry -> entry.getKey() + " = " + entry.getValue())
.collect(Collectors.joining("; " , "[" , "]"));
有没有更快、更好的代码来做到这一点? 在 map 函数中附加键和值似乎成本很高,不是吗?
最佳答案
map -> map.entrySet().stream().map(Entry::toString).collect(joining(";", "[", "]"))
(请注意,我省略了导入。)
I would not worry about performance in this case unless it's a critical part of the system and it's pointed out as a bottleneck by usage of a profiler or a similar tool. If you haven't done this before and you think this code is not optimal, then I̶ ̶k̶n̶o̶w̶ ̶t̶h̶a̶t̶ maybe you're wrong and should test it first.
关于java - 如何使用 Streams 在 Java 8 中将 HashMap 转换为 K/V 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31303273/