Crypt Junior
Crypt Junior

Reputation: 331

Converting ArrayList to a String & Split the results by a ","

Is there a possible solution to convert an ArrayList into a String & split the results by a ",". So I'm trying to think would I add a "," to the string to use split string to split it in different places?

Like so?

  List<String> list = new ArrayList<String>();
        list.add("person1,");
        list.add("person2,");
        list.add("person3,");

        for ( String strs : list ) {
            System.out.print(list);
            strs.split(",");
        }

I know for a fact that the for loop converts the list to a string. I'm trying to achieve these results instead of just getting the ArrayList and having this

[Person1, Person2, Person3]

These are the results I'm trying to achieve. (As a string) not a ArrayList.

Person1, Person2, Person3

Upvotes: 0

Views: 57

Answers (2)

Ali Dehghani
Ali Dehghani

Reputation: 48123

Use String.join():

String.join(", ", list)

This, of course, only works on Java 8 or higher.

Upvotes: 2

Mureinik
Mureinik

Reputation: 311163

Seems as though you want to join the list, not split it:

String result = list.stream().collect(Collectors.joining(", "));

Or more elegantly:

String result = String.join(", ", list);

Upvotes: 1

Related Questions