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

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

DDD
Release: 2024-11-17 09:18:03
Original
891 people have browsed it

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

Converting Comma-Separated Strings to Lists

When working with data in Java, the need often arises to manipulate comma-separated strings. A common problem faced by developers is finding a convenient method to convert these strings into Lists, Vectors, or arrays for further processing.

Java offers a built-in method to streamline this conversion process: Arrays.asList(). This method takes a comma-separated string as input and parses it into a List of individual elements.

The syntax for converting a comma-separated string into a List using Arrays.asList() is:

List<String> items = Arrays.asList(str.split("\s*,\s*"));
Copy after login

where:

  • str is the comma-separated string
  • s,s is the delimiter pattern for splitting the string on commas, optionally surrounded by whitespace

This pattern will split the string on any occurrence of a literal comma, regardless of surrounding whitespace.

For example:

String commaSeparated = "item1 , item2 , item3";
List<String> items = Arrays.asList(commaSeparated.split("\s*,\s*"));
Copy after login

This code will create a list containing the elements ["item1", "item2", "item3"].

Important Note:

It's important to note that Arrays.asList() returns a fixed-size wrapper over an existing array. This means that methods like .remove() cannot be used to modify the resulting List. To obtain a modifiable ArrayList from the result, you must create a new ArrayList instance:

ArrayList<String> itemsModifiable = new ArrayList<>(items);
Copy after login

The above is the detailed content of How to Convert a Comma-Separated String into 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template