How to convert comma-separated String to List? How to convert comma-separated String to List? java java

How to convert comma-separated String to List?


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


Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:

List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));

Or, using Guava:

List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));

Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).


Two steps:

  1. String [] items = commaSeparated.split("\\s*,\\s*");
  2. List<String> container = Arrays.asList(items);