本文翻譯自: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