Main Tutorials

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

References

  1. StringJoiner JavaDoc
  2. Java 8 – StringJoiner example

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Savani
5 years ago

Hi Mkyong, Could you please create tutorials for Spring Cloud ?