Java Map Values to Comma Separated String

Viewed 38288

Is there an effective way to convert java map values to comma separated string using guava or StringUtils?

Map<String, String> testMap = new HashMap<>();
testMap.put("key1", "val1");
testMap.put("key2", "val2");

looking for a way to convert testMap to a String -> "val1,val2".

7 Answers

In Java 1.8, a join() method was added to the String class that can do this.

Also Map has a function values() to get all values. map.values() are string type so just pass to String.join. Example:

Map<String, String> testMap = new HashMap<>();
testMap.put("key1", "val1");
testMap.put("key2", "val2");

String valueString = String.join(",",map.values()); //val1,val2
Related