5

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?

3 Answers 3

22

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 */ ))
Sign up to request clarification or add additional context in comments.

4 Comments

No no i want in Collection<String> and not as List<String>
A List<String> is a Collection<String>. You can change all of the above variable types to Collection<string>
On guava also: Splitter.on(',').splitToList(demoString)
@ToKra that method didn't exist when this answer was written
1

Simple and good,

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.