2

I've been trying to convert a String like this: "[1,2,3]" to an ArrayList in Java. What I tried so far is to use GSon library to convert the String mentioned above to List using:

  1. Gson - convert from Json to a typed ArrayList<T>
  2. Convert Gson Array to Arraylist
  3. Parsing JSON array into java.util.List with Gson

but it ends with an exception (I can provide more details if needed). The first question should be actually if it's a good approach to achieve such a transformation?

pidabrow
  • 966
  • 1
  • 21
  • 47
  • *The first question should be actually if it's a good approach to achieve such a transformation?* Yes, it's fine. *but it ends with an exception (I can provide more details if needed).* Please do. – shmosel Nov 14 '17 at 19:25
  • You could cut the brackets away [ ] and split the string by the coma. Something like: String employee = "Smith,Katie,3014,,8.25,6.5,,,10.75,8.5"; String delims = "[,]"; String[] tokens = employee.split(delims); The tokens array then could be easily converted to an arraylist. – melanzane Nov 14 '17 at 19:31

2 Answers2

4

A non-regex method would be to remove the brackets from the string and then split on the commas. Then convert to an ArrayList.

String s = "[1, 2, 3]";
String[] splits =  s.replace("[","").replace("]","").split(",");
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(splits));
SirCipher
  • 933
  • 1
  • 7
  • 16
0

I suggest you use regular expression to convert the string from "[1,2,3,...]" to "1,2,3,..." and then ue asList() method of Arrays class to convert it to a List.

Refer the following snippet

import java.util.regex.*;
...
...
String str = "[1,2,3,4,5,6,7,8,9,10]";
str = str.replaceAll("[(*)])","$1");
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
H. Sodi
  • 540
  • 2
  • 9