How to convert String into ArrayList properly?

Viewed 88

I want to convert this String into an ArrayList

String

["one","two","three"]

I used this method

List<String> logopath = Arrays.asList(pos.split("\\s*,\\s*"));

I get this output from logopath

0 = "["one""
1 = ""two""
2 = ""three"]"

But I want the output of logopath to be like this:

0 = "one"
1 = "two"
2 = "three"
2 Answers

Your string is actually valid JSON, so I would suggest using a JSON parser here:

String input = "[\"one\",\"two\",\"three\"]";
Gson gson = new Gson();
JsonArray items = gson.fromJson(input, JsonArray.class);
List<String> list = new ArrayList<>();
for (JsonElement item : items) {
    String num = item.getAsString();
    list.add(num);
}

System.out.println(list);

It can be achieved as below,

String input[] = {"one","two","three"};
    List<String> arrList = new ArrayList<>();

    for(String s:input){

        arrList.add(s);
    }
    System.out.print(arrList);
Related