Reputation: 16671
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
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
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
Reputation: 1331
Simple and good,
List<String> list = Arrays.asList(string.split(","))
Upvotes: 1