2

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 2

5

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much , but items is JsonArray but I need List or Arraylist
Might this shorter version work in Java 16? List<String> list = new Gson().fromJson( input, JsonArray.class ).stream().map( JsonElement :: getAsString ).toList()
@Basil More typically I would have given your stream version (or something close to it), but I answered on a cell phone and so would not have been able to test it.
@BasilBourque thank you, that should basically work too , but I use java 1.7 so I think I cannot use stream.
0

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);

1 Comment

Thanks, but my String is just string not string[] , so I cannot apply it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.