snippetjavaCritical
How to convert comma-separated String to List?
Viewed 0 times
howcommaconvertseparatedliststring
Problem
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 that?
String commaSeparated = "item1 , item2 , item3";
List items = //method that converts above string into list??Solution
Convert comma separated String to List
The above code splits the string on a delimiter defined as:
Please note that this returns simply a wrapper on an array: you CANNOT for example
List 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.Code Snippets
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));Context
Stack Overflow Q#7488643, score: 1185
Revisions (0)
No revisions yet.