In Java, manipulating and storing collections of data in an organized manner is often necessary. A common scenario involves converting a comma-separated string into a list, such as converting "item1, item2, item3" into ["item1", "item2", "item3"].
The Java API doesn't provide a direct method to perform this conversion. Therefore, it's necessary to resort to custom code.
To convert a comma-separated string to a list, you can use the following approach:
String commaSeparated = "item1 , item2 , item3"; List<String> items = Arrays.asList(str.split("\s*,\s*"));
Explanation:
Note:
The resulting list will be a wrapper around the array, meaning you cannot perform operations like .remove() on it. To obtain a true ArrayList, you can use:
List<String> items = new ArrayList<>(Arrays.asList(str.split("\s*,\s*")));
The above is the detailed content of How to Convert a Comma-Separated String to a List in Java?. For more information, please follow other related articles on the PHP Chinese website!