Reputation: 13
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
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