Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a HashMap to a K/V-String in Java 8 with Streams

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?

like image 428
Joel Avatar asked Jul 08 '15 20:07

Joel


People also ask

Can we convert map to stream in java?

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.

How do you convert a map key and value in a string?

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.


1 Answers

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.

like image 100
gdejohn Avatar answered Oct 11 '22 08:10

gdejohn