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.
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
4
public class Example1 {
5
6
public static void main(String[] args) {
7
8
String text = "a, b, c";
9
List<String> list = Arrays.asList(text.split("\\s*,\\s*"));
10
11
System.out.println(list); // [a, b, c]
12
}
13
}
Output:
xxxxxxxxxx
1
[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.
To convert list of Strings to comma separated String, we can use Java 8 String.join method on ',' character.
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
4
public class Example2 {
5
6
public static void main(String[] args) {
7
8
List<String> list = Arrays.asList("a", "b", "c");
9
String text = String.join(",", list);
10
11
System.out.println(text); // a,b,c
12
}
13
}
Output:
xxxxxxxxxx
1
a,b,c