You could do this:
String str = "...";
List<String> elephantList = Arrays.asList(str.split(", "));
In Java 9+, create an unmodifiable list with List.of.
List<String> elephantList = List.of(str.split(", ")); // Unmodifiable list.
Basically the .split() method will split the string according to (in this case) delimiter you are passing and will return an array of strings.
However, you seem to be after a List of Strings rather than an array. So the array must be turned into a list. We can turn that array into a List object by calling either Arrays.asList() or List.of.
FYI you could also do something like so:
String str = "...";
ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));
But it is usually better practice to program to an interface rather than to an actual concrete implementation. So I would not recommend this approach.
Answer from npinti on Stack OverflowYou could do this:
String str = "...";
List<String> elephantList = Arrays.asList(str.split(", "));
In Java 9+, create an unmodifiable list with List.of.
List<String> elephantList = List.of(str.split(", ")); // Unmodifiable list.
Basically the .split() method will split the string according to (in this case) delimiter you are passing and will return an array of strings.
However, you seem to be after a List of Strings rather than an array. So the array must be turned into a list. We can turn that array into a List object by calling either Arrays.asList() or List.of.
FYI you could also do something like so:
String str = "...";
ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));
But it is usually better practice to program to an interface rather than to an actual concrete implementation. So I would not recommend this approach.
Well, you want to split, right?
String animals = "dog, cat, bear, elephant, giraffe";
String[] animalsArray = animals.split(",");
If you want to additionally get rid of whitespaces around items:
String[] animalsArray = animals.split("\\s*,\\s*");
Videos
You may use a set of chars as separator as described in Pattern
String string = "One step at,,a, time ,.";
System.out.println( Arrays.toString( string.split( "[\\s,]+" )));
Output:
[One, step, at, a, time, .]
\s : A whitespace character: [ \t\n\x0B\f\r]
[abc] : a, b, or c (simple class)
Greedy quantifiers X+ : X, one or more times
Solution:
String.split("[ ,]+"); // split on on one or more spaces or commas
[] - simple character class
[, ] - simple character class containing space or comma
[ ,]+ - space or comma showing up one or more times
Example:
String source = "A B C,,D, E ,F";
System.out.println(Arrays.toString(source.split("[, ]+")));
Output:
[A, B, C, D, E, F]