Java – Convert comma-separated String to a List
Java examples to show you how to convert a comma-separated String into a List and vice versa.
1. Comma-separated String to List
TestApp1.java
package com.mkyong.utils;
import java.util.Arrays;
import java.util.List;
public class TestApp1 {
public static void main(String[] args) {
String alpha = "A, B, C, D";
//Remove whitespace and split by comma
List<String> result = Arrays.asList(alpha.split("\\s*,\\s*"));
System.out.println(result);
}
}
Output
[A, B, C, D]
2. List to Comma-separated String
No need to loop the List
, uses the new Java 8 String.join
TestApp2.java
package com.mkyong.utils;
import java.util.Arrays;
import java.util.List;
public class TestApp2 {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
String result = String.join(",", list);
System.out.println(result);
}
}
Output
A,B,C,D
Hi Mkyong, Could you please create tutorials for Spring Cloud ?