user9880920
user9880920

Reputation: 13

Convert a comma separated string to list which has a comma at the last

I have the below string which has a comma at the last. I want to convert the string to list. I am using the below code to do it.

public class TestClass {
    public static void main(String[] args) {

        String s = "2017-07-12 23:40:00.0,153.76,16.140,60.00,,56.00,";
        String [] items = s.split(",");
        
        List<String> splittedString = new ArrayList<String>(Arrays.asList(items));
        for (String s1 : splittedString) {
            System.out.println(s1);
        }
        System.out.println("Here");
    }
}

Here the last comma is not being considered as a list element. How can I change this code so that it works?

Actual Output:-

2017-07-12 23:40:00.0
153.76
16.140
60.00

56.00
Here

Expected output:-

2017-07-12 23:40:00.0
153.76
16.140
60.00

56.00

Here

Upvotes: 1

Views: 54

Answers (2)

Amit Bera
Amit Bera

Reputation: 7325

This is the expected behavior of String#split.

As per java docs.

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.

Upvotes: 1

NiVeR
NiVeR

Reputation: 9796

Change the split line to:

String [] items = s.split(",", -1);

and it should do as you expect. This is the version with the limit. Check the reference.

Upvotes: 3

Related Questions