Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

Java - convert comma separated String to ArrayList

0 contributions
4 points

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more