Effortlessly Convert Comma-Separated Strings to Lists
Java offers a convenient method to transform comma-delimited strings into List objects. This eliminates the need for custom code and simplifies the process.
Suppose we have a string like "item1 , item2 , item3". To convert it into a List of strings, we can use the following code snippet:
String commaSeparated = "item1 , item2 , item3"; List<String> items = Arrays.asList(str.split("\s*,\s*"));
The heart of this code is the split() method. It divides the string into individual substrings using the specified delimiter. In our case, the delimiter is a comma with optional whitespace on both sides.
The resulting substrings are then stored in an array, which is then wrapped into a List object. This List provides convenient access to the individual elements, making it easier to work with the data.
Note that the resulting List is initially just a wrapper around an array. If you need a true ArrayList with full modification capabilities, you can use the following code:
List<String> items = new ArrayList<>(Arrays.asList(str.split("\s*,\s*")));
Converting comma-separated strings to Lists in Java is a simple and efficient operation. By leveraging the built-in split() method, developers can save time and effort while ensuring accuracy in data manipulation.
The above is the detailed content of How Can I Easily Convert Comma-Separated Strings to Lists in Java?. For more information, please follow other related articles on the PHP Chinese website!