Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert comma-separated String to List?

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<String> items = //method that converts above string into list?? 
like image 236
Jame Avatar asked Sep 20 '11 16:09

Jame


People also ask

How do you convert comma separated numbers to lists in Python?

Input a comma - separated string using raw_input() method. Split the elements delimited by comma (,) and assign it to the list, to split string, use string. split() method. The converted list will contains string elements.

How do you convert a comma separated string to a list in Pyspark?

In pyspark SQL, the split() function converts the delimiter separated String to an Array. It is done by splitting the string based on delimiters like spaces, commas, and stack them into an array. This function returns pyspark.


1 Answers

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>.

like image 146
AlexR Avatar answered Sep 21 '22 14:09

AlexR