I converted the ArrayList<String> list which contains "String1", "String2" to String by using list.toString(). The resulted string format is [String1, String2]. Is there any way to convert this result back to ArrayList<String>?
3 Answers
Try applying the following code
String value = "[String1,String2,String3]";
value = value.subString(1,value.length()-1);
String[] split = value.split(",");
List<String> sampleList = Arrays.asList(split);
4 Comments
Dawood ibn Kareem
No. This won't necessarily give an
ArrayList, which is what the question asked for. The right hand side of the last line needs to be new ArrayList<String>(Arrays.asList(split)).Woody
@David Wallace, thanks for your suggestion. why the right hand side of the last line needs to be new ArrayList<String>(Arrays.asList(split))? Can you please clear my doubt?
Dawood ibn Kareem
Just because the OP said he wanted to have the result as an
ArrayList, but the specification for Arrays.asList doesn't require that it returns an ArrayList. I believe that the current version of Java 7 does in fact return an ArrayList from Arrays.asList; but it's not required to by the specification, and a future version may return something different.Woody
@David Wallace, thank you. Will follow your valuable feedback when I work on the same in future.
create a new Class extending Array List
public class CustomArrayList<Item> extends ArrayList<Item> {
and override
toString
method, which could give a comma separated String representation. Now use
new CustomArrayList<Item>(Arrays.asList(list.toString().split(",")))
to get it back in ArrayList.
Comments
No direct way. Just get that String remove those [] from String and then split by , then add back to list.
Something like this,considering the given format.
String s = "[String1, String2]";
s = s.substring(1, s.length() - 1);
List<String> list = new ArrayList<>();
for (String string : s.split(",")) {
list.add(string.trim());
}
1 Comment
chrylis -cautiouslyoptimistic-
Note that this isn't foolproof; if the internal strings have
, (note the space, which should go in split), then you will end up with extra strings.
splitmethod of theStringclass - it may be what you are looking for.ArrayList<String>into aString[]with thetoArraymethod.list.toString()is reversable or not.