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 the Author

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

Comments

Leave a Reply

avatar
newest oldest most voted
Savani
Guest
Savani

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