Languages
[Edit]
EN

Java - convert comma separated String to ArrayList

4 points
Created by:
Root-ssh
175450

In this post we convert comma separated String to list and back again from list of strings to comma separated String.

1. Convert comma separated String to List<String>

import java.util.Arrays;
import java.util.List;

public class Example1 {

    public static void main(String[] args) {

        String text = "a, b, c";
        List<String> list = Arrays.asList(text.split("\\s*,\\s*"));

        System.out.println(list); // [a, b, c]
    }
}

Output:

[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.

2. Convert List<String> to comma separated String

To convert list of Strings to comma separated String, we can use Java 8 String.join method on ',' character.

import java.util.Arrays;
import java.util.List;

public class Example2 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("a", "b", "c");
        String text = String.join(",", list);

        System.out.println(text); // a,b,c
    }
}

Output:

a,b,c

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join