Java Convert comma-separated String to a List
By:Roy.LiuLast updated:2019-08-11
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
References
From:一号门
Previous:Apache Solr Hello World Example
COMMENTS