EN
Java - convert comma separated String to ArrayList
4
points
In this post we convert comma separated String to list and back again from list of strings to comma separated String.
1. Convert comma separated String to List<String>
import java.util.Arrays;
import java.util.List;
public class Example1 {
public static void main(String[] args) {
String text = "a, b, c";
List<String> list = Arrays.asList(text.split("\\s*,\\s*"));
System.out.println(list); // [a, b, c]
}
}
Output:
[a, b, c]
In this example we use regex:
\s*,\s*
It removes whitespace from left and right side and split our String by comma.
2. Convert List<String> to comma separated String
To convert list of Strings to comma separated String, we can use Java 8 String.join method on ',' character.
import java.util.Arrays;
import java.util.List;
public class Example2 {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
String text = String.join(",", list);
System.out.println(text); // a,b,c
}
}
Output:
a,b,c