java - 如何使用 Streams 在 Java 8 中将 HashMap 转换为 K/V 字符串

标签 java hashmap java-8 java-stream

我想为我的 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(";", "[", "]"))

(请注意,我省略了导入。)

Luiggi Mendoza说:

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/

相关文章:

java - 什么是 com.sun.media.sound.PortMixer-s 类?

java - 拥有无边框的 JToggleButton?

java - 在设定的时间段后从缓存中删除项目?

java - 我的 HashMap 仅放置空值

java - 使用流计算对象的多个字段

java - 在 StringUtils 中返回可选是否过度?

java - ArrayList 引用行为

java - 尝试在 NfcManager.start() 上获取空数组的长度

java - 比较两个映射并删除所有具有相同键或相同值的元素

datetime - 无法将当天的个位数小时和小写 am-pm 解析为 Java 8 LocalTime