Reputation: 1833
I want to create a string of the key value pairs of my HashMap<String, String> m
as fast as possible.
I tried:
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("]");
With Java8 I tried:
m.entrySet().stream()
.map(entry -> entry.getKey() + " = " + entry.getValue())
.collect(Collectors.joining("; " , "[" , "]"));
Is there any faster, better code to do that? It seems to be costly to append the keys and Values in the map function, doesn't it?
Upvotes: 7
Views: 8403
Reputation: 7579
map -> map.entrySet().stream().map(Entry::toString).collect(joining(";", "[", "]"))
(Note that I omitted the imports.)
Like Luiggi Mendoza said:
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.
Upvotes: 8
Reputation: 2584
@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()));
}
Upvotes: -1
Reputation: 921
Use StringBuilder instead of buffer.
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
Upvotes: 0