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".
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.
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 (","))
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.
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.
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(","));
Guava: Joiner.on(',').join(map.values())
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With