Home >Java >javaTutorial >How to Convert a Comma-Separated String into an ArrayList in Java?

How to Convert a Comma-Separated String into an ArrayList in Java?

DDD
DDDOriginal
2024-11-02 10:54:02961browse

How to Convert a Comma-Separated String into an ArrayList in Java?

Dividing a Comma-Separated String into an ArrayList

When working with strings, the need may arise to split a string into its individual elements based on a specific delimiter. This is often necessary to process data stored as comma-separated values (CSV). Here, we explore an optimal approach to split a comma-separated string into an ArrayList.

To efficiently achieve this, you can utilize Java's built-in .split() method on the String object. This method accepts a delimiter as its parameter and returns an array of strings containing the individual elements separated by the delimiter.

<code class="java">String str = "...";
List<String> elephantList = Arrays.asList(str.split(","));</code>

The .split() method splits the string into individual elements and returns an array of these elements. However, since you desire an ArrayList of Strings rather than an array, you can convert the array to a list using the Arrays.asList() utility.

<code class="java">String str = "...";
ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));</code>

While both options achieve the desired result, it is recommended to adhere to the principle of programming to an interface rather than a concrete implementation. Therefore, it is advisable to prefer the first approach, which provides a more general solution that can accommodate different scenarios.

The above is the detailed content of How to Convert a Comma-Separated String into an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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