Java Map Values to Comma Separated String

l a s picture l a s · Dec 26, 2013 · Viewed 34.8k times · Source

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".

Answer

lreeder picture lreeder · Jul 2, 2015

Here's how to do it in Java 8+ (doesn't require Guava, StringUtils, or other external libraries):

testMap.values().stream().map(Object::toString).collect(Collectors.joining(","));