How to create a Collection <String> object from comma separated values

I have a string object like

final String demoString = "1,2,19,12"; 

Now I want to create a collection from it.

How can i do this??

+4
source share
2 answers

guavas:

 List<String> it = Splitter.on(',').splitToList(demoString); 

Standard JDK:

 List<String> list = Arrays.asList(demoString.split(",")) 

Commons / Lang:

 List<String> list = Arrays.asList(StringUtils.split(demoString, ",")); 

Please note that you cannot add or remove items from the list created by Arrays.asList, since the list is maintained by the array and the arrays cannot be modified. If you need to add or remove elements, you need to do this:

 // This applies to all examples above List<String> list = new ArrayList<String>(Arrays.asList( /*etc */ )) 
+20
source

Simple and good

 List<String> list = Arrays.asList(string.split(",")) 
+1
source

All Articles