This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

The problem:

How do I convert a comma-separated string into a list? Is there a built-in Java method for converting comma-separated strings into some kind of container (such as an array, list, or vector)? Or do I need to write custom code to implement it?

String commaSeparated = "item1 , item2 , item3"; List<String> items = // Implement conversion code??Copy the code

The popular answer:


Answer 1:

Convert a comma-separated string to a list:

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

The above code breaks up the string separated by zero or more Spaces, literal commas, and zero or more Spaces. Then place the split words in the list and remove the space between the split words and the comma. Note that this only returns the wrapper class of the array: for example, it cannot be removed from the result.remove (). If you want to actually use ArrayList, you must further wrap it with New ArrayList.

Answer 2:

Arrays.aslist returns a list of fixed sizes supported by Arrays. If you want a plain mutable java.util.arrayList, do the following:

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

Or use Guava:

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

Using a splitter gives you more flexibility to split strings, and you can skip empty strings in results and trim results. It also behaves less oddly than String.split, and does not require a regex split (which is just an option).

Translated from Stack Overflow