Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map Values to Comma Separated String

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

like image 210
l a s Avatar asked Dec 26 '13 16:12

l a s


People also ask

How to convert list of string to comma separated string in Java?

Given a List of String, the task is to convert the List to a comma separated String in Java. Approach: This can be achieved with the help of join () method of String as follows. Get the List of String. Form a comma separated String from the List of String using join () method by passing comma ‘, ‘ and the list as parameters. Print the String.

How do I convert a string to a map in Java?

Convert a String to a Map Using Streams To perform conversion from a String to a Map, let's define where to split on and how to extract keys and values: public Map<String, String> convertWithStream(String mapAsString) { Map<String, String> map = Arrays.stream (mapAsString.split (","))

How to convert ArrayList to comma-separated strings in Apache Commons?

Apache Commons library has a StringUtils class that provides a utility function for the string. The join method is used to convert ArrayList to comma-separated strings. OutputDataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases Stream API was introduced in Java 8 and is used to process collections of objects.

How to convert a map to a string in Apache Commons?

Convert a Map to a String Using Apache Commons The joining is very straightforward – we just need to call the StringUtils.join method: One special mention goes to the debugPrint method available in Apache Commons. It is very useful for debugging purposes.


2 Answers

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(","));
like image 139
lreeder Avatar answered Oct 20 '22 14:10

lreeder


Guava: Joiner.on(',').join(map.values()).

like image 23
Louis Wasserman Avatar answered Oct 20 '22 15:10

Louis Wasserman