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

I want to create a string as quickly as possible from a pair of key values ​​of my HashMap<String, String> m .

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 a faster, better code for this? It seems expensive to have keys and values ​​in a map function, right?

+6
source share
3 answers
 map -> map.entrySet().stream().map(Entry::toString).collect(joining(";", "[", "]")) 

(Please note that I skipped the import.)

As Luigi Mendoza said:

I would not worry about performance in this case, if this is not a critical part of the system, and this was indicated as a bottleneck when using a profiler or similar tool. If you have not done this before, and you think this code is not optimal, then I̶ ̶k̶n̶o̶w̶ ̶t̶h̶a̶t̶, you may be mistaken and should test it first.

+8
source

Use StringBuilder instead of a buffer.

Javadoc => StringBuffer Class

"The StringBuilder class should usually be used in preference to this because it supports all the same operations, but faster because it does not synchronize." Class stringbuffer

0
source
 @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())); } 
-1
source

All Articles