0 votes
1 view
in Java by (5.3k points)
edited by

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";
ArrayList<String> items = //method that converts above string into list??

1 Answer

0 votes
by (32.7k points)

Use this built-in method:-

List<String> items = Arrays.asList(str.split("\\s*,\\s*"));

The above code breaks the string on a delimiter fixed as zero or more whitespace, a written comma, zero or added whitespace which will put the words into the list and drop any whitespace between the words and commas.

P.S- This will simply pass a wrapper on an array: you can't, for example, .remove() from the resulting list. For a concrete ArrayList, you must further use a new ArrayList<String>.

...