Home > Java > javaTutorial > How Can I Easily Convert Comma-Separated Strings to Lists in Java?

How Can I Easily Convert Comma-Separated Strings to Lists in Java?

Mary-Kate Olsen
Release: 2024-12-01 18:37:15
Original
334 people have browsed it

How Can I Easily Convert Comma-Separated Strings to Lists in Java?

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*"));
Copy after login

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*")));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template