3

How to convert the below string into java ArrayList?

I tried with line :

"GOC,,404719160795907,911367109182460,218.248.72.40,62944,31,3331,31425,3544151354,117.200.252.120,bsnlnet,2,100.115.103.86,0,0,0,20190225123602,20190225125558,1196,,0,,,,,5428665,0,mnc071.mcc404.gprs,9448861612,Prepaid,1,,,2,255,,,,"

List<String> data = new ArrayList<>(Arrays.asList(line.split(",")))

but the problem is it is converting upto 255(Column) and size of the array has come to 36, but it should be 40

1
  • Do you want to keep the empty elements? Commented Feb 26, 2019 at 9:56

1 Answer 1

8

From the documentation of String.split(String):

Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

You see that empty strings are not included into your array, and because your line ends with ,,,, you'll lose those 4 elements, leaving you with a List of size 36.

To include the last elements you need to call the overload String.split(String, int), like this:

List<String> data = new ArrayList<>(Arrays.asList(line.split(",", -1)));

From the documentation:

[...] If n (the second parameter to split()) is non-positive then the pattern will be applied as many times as possible and the array can have any length. [...]

Sign up to request clarification or add additional context in comments.

1 Comment

instead of single comma "," better to use this regex ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)" - this data looks like CSV.

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.