Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for t
Same result you can achieve using the Splitter class.
var list = Splitter.on(",").splitToList(YourStringVariable)
(written in kotlin)
There are many ways to solve this using streams in Java 8 but IMO the following one liners are straight forward:
String commaSeparated = "item1 , item2 , item3";
List<String> result1 = Arrays.stream(commaSeparated.split(" , "))
.collect(Collectors.toList());
List<String> result2 = Stream.of(commaSeparated.split(" , "))
.collect(Collectors.toList());
I usually use precompiled pattern for the list. And also this is slightly more universal since it can consider brackets which follows some of the listToString expressions.
private static final Pattern listAsString = Pattern.compile("^\\[?([^\\[\\]]*)\\]?$");
private List<String> getList(String value) {
Matcher matcher = listAsString.matcher((String) value);
if (matcher.matches()) {
String[] split = matcher.group(matcher.groupCount()).split("\\s*,\\s*");
return new ArrayList<>(Arrays.asList(split));
}
return Collections.emptyList();
In Kotlin if your String list like this and you can use for convert string to ArrayList use this line of code
var str= "item1, item2, item3, item4"
var itemsList = str.split(", ")
Convert comma separated String to List
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace
which will place the words into the list and collapse any whitespace between the words and commas.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove()
from the resulting List
. For an actual ArrayList
you must further use new ArrayList<String>
.
Here is another one for converting CSV to ArrayList:
String str="string,with,comma";
ArrayList aList= new ArrayList(Arrays.asList(str.split(",")));
for(int i=0;i<aList.size();i++)
{
System.out.println(" -->"+aList.get(i));
}
Prints you
-->string
-->with
-->comma