Converting Comma-Separated Strings to Lists
When working with data in Java, the need often arises to manipulate comma-separated strings. A common problem faced by developers is finding a convenient method to convert these strings into Lists, Vectors, or arrays for further processing.
Java offers a built-in method to streamline this conversion process: Arrays.asList(). This method takes a comma-separated string as input and parses it into a List of individual elements.
The syntax for converting a comma-separated string into a List using Arrays.asList() is:
List<String> items = Arrays.asList(str.split("\s*,\s*"));
where:
This pattern will split the string on any occurrence of a literal comma, regardless of surrounding whitespace.
For example:
String commaSeparated = "item1 , item2 , item3"; List<String> items = Arrays.asList(commaSeparated.split("\s*,\s*"));
This code will create a list containing the elements ["item1", "item2", "item3"].
Important Note:
It's important to note that Arrays.asList() returns a fixed-size wrapper over an existing array. This means that methods like .remove() cannot be used to modify the resulting List. To obtain a modifiable ArrayList from the result, you must create a new ArrayList instance:
ArrayList<String> itemsModifiable = new ArrayList<>(items);
The above is the detailed content of How to Convert a Comma-Separated String into a List in Java?. For more information, please follow other related articles on the PHP Chinese website!