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?
Converting complete Map<Key, Value> into Stream: This can be done with the help of Map. entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.
We can convert a map to a string in java using two array lists. In this, we first fill the map with the keys. Then, we will use keySet() method for returning the keys in the map, and values() method for returning the value present in the map to the ArrayList constructor parameter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With