Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k 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 (46k 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>.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...