Home > Java > javaTutorial > body text

How to Convert a Comma-Separated String to a List in Java?

Susan Sarandon
Release: 2024-11-20 12:23:09
Original
837 people have browsed it

How to Convert a Comma-Separated String to a List in Java?

Converting Comma-Separated Strings to Lists

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"].

Built-in Method

The Java API doesn't provide a direct method to perform this conversion. Therefore, it's necessary to resort to custom code.

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

Explanation:

  1. The split() method is used to split the input string into tokens based on the delimiter, which is defined as zero or more whitespace characters followed by a literal comma followed by zero or more whitespace characters again.
  2. The resulting tokens are stored in an array of strings.
  3. The Arrays.asList() method is used to convert the array into a list, which is backed by the original array.

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

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!

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