Saurabh Kumar
Saurabh Kumar

Reputation: 16671

How to make 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<String> from it. How can I do that?

Upvotes: 5

Views: 51573

Answers (3)

Ajay Singh
Ajay Singh

Reputation: 501

you can create a List<String> and assign it to Collection<String> as List extends Collection.

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

Collection<String> collection = List.of(demoString.split(","));

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299048

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 */ ))

Upvotes: 22

Sathwick
Sathwick

Reputation: 1331

Simple and good,

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

Upvotes: 1

Related Questions