Languages
[Edit]
EN

Java - convert comma separated String to ArrayList

4 points
Created by:
Root-ssh
6442

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

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.