Convert comma seperated string to arraylist with trailing comma sepearted

sriman narayana :

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

Lino :

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. [...]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86406&siteId=1