天天看点

如何将逗号分隔的String转换为ArrayList?

本文翻译自:How to convert comma-separated String to ArrayList?

Is there any built-in method in Java which allows us to convert comma separated String to some container (eg array, List or Vector)?

Java中是否有任何内置方法允许我们将逗号分隔的String转换为某个容器(例如数组,List或Vector)?

Or do I need to write custom code for that?

或者我需要为此编写自定义代码?
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = //method that converts above string into list??
           

#1楼

参考:https://stackoom.com/question/VQ8Z/如何将逗号分隔的String转换为ArrayList

#2楼

在groovy中,您可以使用tokenize(Character Token)方法:

list = str.tokenize(',')
           

#3楼

An example using

Collections

.

使用

Collections

的示例。
import java.util.Collections;
 ...
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
 ...
           

#4楼

Here is another one for converting CSV to ArrayList:

这是另一个将CSV转换为ArrayList的方法:
String str="string,with,comma";
ArrayList aList= new ArrayList(Arrays.asList(str.split(",")));
for(int i=0;i<aList.size();i++)
{
    System.out.println(" -->"+aList.get(i));
}
           

Prints you

打印你
-->string - >字符串 -->with - >使用 -->comma - >逗号

#5楼

This code will help,

这段代码会有所帮助,
String myStr = "item1,item2,item3";
List myList = Arrays.asList(myStr.split(","));
           

#6楼

List commaseperated = new ArrayList();
String mylist = "item1 , item2 , item3";
mylist = Arrays.asList(myStr.trim().split(" , "));

// enter code here