For completeness, using the Guava library, you'd do: Splitter.on(",").split(“dog,cat,fox”)
Another example:
String animals = "dog,cat, bear,elephant , giraffe , zebra ,walrus";
List<String> l = Lists.newArrayList(Splitter.on(",").trimResults().split(animals));
// -> [dog, cat, bear, elephant, giraffe, zebra, walrus]
Splitter.split()
returns an Iterable, so if you need a List, wrap it in Lists.newArrayList()
as above. Otherwise just go with the Iterable, for example:
for (String animal : Splitter.on(",").trimResults().split(animals)) {
// ...
}
Note how trimResults()
handles all your trimming needs without having to tweak regexes for corner cases, as with String.split()
.
If your project uses Guava already, this should be your preferred solution. See Splitter documentation in Guava User Guide or the javadocs for more configuration options.