Convert comma separated String to List
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.
Convert comma separated String to List
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.
Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:
List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
Or, using Guava:
List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));
Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).
array - Java split a string into ArrayList - Code Review Stack Exchange
regex - Splitting a string into a list in Java - Stack Overflow
[Java] Splitting Strings and creating an ArrayList with the substrings
java - How to split a String to an ArrayList? - Stack Overflow
There are many encoding formats that could lead to this string. One of them is JSON. So instead of writing the splitting code yourself, you should use one of the many existing JSON parsers. Have a look at the awesome-java project at GitHub to find one.
Then, your code should become as simple as:
JSONArray sampleList = JSON.parseArray(sample);
I would say it depends on what the code is for.
If it's a write once quick solution for some small task your current code is fine as it is. The idea here is that if it no longer does what you want, you don't mind rewriting it entirely since it was a quick and (not so) dirty solution in the first place.
If instead you intend to use this as part of a bigger project that you plan on maintaining/improving you might want to look into JSON-parsing like Roland Illig suggests.
You didn't mention where the string originates from. If you're able to change that code as well you can also take a look at alternatives. For example JSON/XML serialisation/deserialisation of an entire class.
Do you mean you want it split "whenever you see : or , or " or { or [ or } or ]"? If so, you really don't need to say much more than:
.split("[:,\"{\\[ }\\]]")
I.e. "split on any character in the following character class definition: :,"{[ }]", where we use the standard regexp character class definition syntax ([...]) with appropriate escaping.
Normally this means a regex that looks like /[:,"{\[ }\]]/ but because you're writing a regex inside of a normal string, more escapes are needed: " needs regular string escaping so your string doesn't end prematurely (so that becomes \"), and [ and ] are active characters in the regexp, so they need \ before them in the regex. However, we can't just put \ in the string and have it work because \ is the escape character, so we need to "escape the escape" which means using \\ (giving \\[ and \\]).
String[] result = "a:b,c\"d{e[f g}h]i".split("[:,\"{\\[ }\\]]");
System.out.print(result.length);
// => result has 9 elements in it, ['a',...,'i']
It's not compiling because you didn't escape the quotation mark, but the backslash itself.
Change:
\\"
To:
\"
I have a few classes in this program sending and returning values among themselves. This one reads a string from another class and has to split the string to substrings and return the strings broken into <Box> objects as an ArrayList.
I have tried multiple methods, but nothing seems to work.
public class Converter {
private String s;
public Converter(String s) {
this.s = s;
}
public ArrayList<Box> convert() {
String[] tokens = s.split(",");
Box box1 = new Box(tokens[0]);
Box box2 = new Box(tokens[1]);
Box box3 = new Box(tokens[2]);
Box box4 = new Box(tokens[3]);
Box box5 = new Box(tokens[4]);
Box box6 = new Box(tokens[5]);
Box box7 = new Box(tokens[6]);
Box box8 = new Box(tokens[7]);
ArrayList<Box> list = new ArrayList<Box>(Arrays.asList(tokens));
return list;
}
}I am getting “cannot resolve constructor ‘ArrayList(java.util.List<T>” at the Array.asList part.
Any suggestions?
You can create an ArrayList from the array via Arrays.asList:
ArrayList<String> parts = new ArrayList<>(
Arrays.asList(textField.getText().split(",")));
If you don't need it to specifically be an ArrayList, and can use any type of List, you can use the result of Arrays.asList directly (which will be a fixed-size list):
List<String> parts = Arrays.asList(textField.getText().split(","));
There is no such thing as a Split functionfor list, but you can do the split and then convert to a List
List myList = Arrays.asList(myString.split(","));