如何使用 Streams 在 Java 8 中将 HashMap 转换为 K/V-String
How to convert a HashMap to a K/V-String in Java 8 with Streams
我想尽快创建我的 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 函数中附加 keys 和 Values 似乎很昂贵,不是吗?
使用 StringBuilder 而不是缓冲区。
Javadoc => Class StringBuffer
"The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization." Class StringBuffer
@Test
public void testMapPrint() {
Map<String, String> map = new HashMap<>();
map.put("a", "b");
map.put("c", "d");
map.entrySet().stream()
.forEach(entry -> System.out.println(entry.getKey() + ":" + entry.getValue()));
}
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.
我想尽快创建我的 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 函数中附加 keys 和 Values 似乎很昂贵,不是吗?
使用 StringBuilder 而不是缓冲区。
Javadoc => Class StringBuffer
"The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization." Class StringBuffer
@Test
public void testMapPrint() {
Map<String, String> map = new HashMap<>();
map.put("a", "b");
map.put("c", "d");
map.entrySet().stream()
.forEach(entry -> System.out.println(entry.getKey() + ":" + entry.getValue()));
}
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.