0

How do I convert the text

"[user1, 1, 2, 3, 4, 5]"

into an ArrayList? Please note that each element should be a string.

Such to say:

String str = "[user1,  1,  2,  3,  4,  5]"
ArrayList<> aryList = ...

Thanks.

7
  • 1
    Possible duplicate of Creating an Arraylist of Objects Commented Sep 17, 2019 at 18:34
  • @WJS Is there a way to do it without Objects? It's for a project and we have to write accompanying pseudocode (for some reason ik) and the guide doesn't specify how to convert Objects into pseudocode Commented Sep 17, 2019 at 18:36
  • Use String.split()` on the commas to get an array of tokens Then you can fill an array list of string by iterating over the tokens. Use List<String> list = new ArrayList<>() ` to create the list. You will need to clean up your tokens somewhat (e.g. braces, etc). Commented Sep 17, 2019 at 18:37
  • List<String> aryList = Arrays.asList(str.substring(1, str.length() -1).split(",\\s*")); Commented Sep 17, 2019 at 18:39
  • If I use split(), The first value, for example, would be "[user1" and I don't want that bracket Commented Sep 17, 2019 at 18:39

2 Answers 2

0

this answer hold good only in case you are have a string starting with [ and ending with ] i took an example from your question. you have many ways to delimit the string and split it to list of string. @Note : i have just wrote a test method so that you can test the code

@Test
public void test(){
    String value = "[user1, 1, 2, 3, 4, 5]";
    List<String> valueList = Arrays.asList(value.substring(value.indexOf('[')+1, value.lastIndexOf(']')).split(","));
    System.out.println("Value list is "+valueList);
}
Sign up to request clarification or add additional context in comments.

Comments

0

In pure Java, you could just remove the braces and then split the string on the comma and two spaces that you have delimiting each entry:

String text = "[user1,  1,  2,  3,  4,  5]";

// This will create a List of 6 strings:
List<String> splitList = Arrays.asList(text.replaceAll("[", "").replaceAll("]", "").split(",  "));

If the entries in your array are quoted, then this syntax is just the syntax for arrays in JSON. You could use a Jackson ObjectMapper to read the string to a list:

ObjectMapper mapper = new ObjectMapper();
String text = "[\"user1\",  \"1\",  \"2\",  \"3\",  \"4\",  \"5\"]";
List<String> splitStrings = objectMapper.readValue(text, new TypeReference<List<String>>(){});

Comments

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.