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.

  • 1
    Possible duplicate of [Creating an Arraylist of Objects](https://stackoverflow.com/questions/3982550/creating-an-arraylist-of-objects) – WJS Sep 17 '19 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 – user8494778 Sep 17 '19 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 list = new Arra`yList<>() ` to create the list. You will need to clean up your tokens somewhat (e.g. braces, etc). – WJS Sep 17 '19 at 18:37
  • `List aryList = Arrays.asList(str.substring(1, str.length() -1).split(",\\s*"));` – Youcef LAIDANI Sep 17 '19 at 18:39
  • If I use split(), The first value, for example, would be "[user1" and I don't want that bracket – user8494778 Sep 17 '19 at 18:39
  • Use String.substring(1, string.length() -1). You may also want to trim the white space off each token. – WJS Sep 17 '19 at 18:40
  • Thanks @WJS and YCF_L. Your suggestions work :) – user8494778 Sep 17 '19 at 18:43

2 Answers2

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);
}
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>>(){});
Daniel Kesner
  • 226
  • 4
  • 16