Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I have a String object like

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

Now I want to create a Collection<String> from it. How can I do that?

like image 250
Saurabh Kumar Avatar asked Nov 29 '22 04:11

Saurabh Kumar


2 Answers

Guava:

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, ","));

Note that you can't add or remove Elements from a List created by Arrays.asList, since the List is backed by the supplied array and arrays can't be resized. 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 */ ))
like image 147
Sean Patrick Floyd Avatar answered Dec 15 '22 03:12

Sean Patrick Floyd


Simple and good,

List<String> list = Arrays.asList(string.split(","))
like image 38
Sathwick Avatar answered Dec 15 '22 02:12

Sathwick