Languages

Java - convert Array to comma separated String

3 points
Asked by:
Root-ssh
7497

Is there easier way to convert Array of Strings to comma separated String in java?

I guess maybe it is possible using streams and java 8?

My current code works, but it's kind of long and messy..

public class JoinerExample {

    public static void main(String[] args) {

        String[] users = {"Ann", "John", "Kate"};
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < users.length; i++) {
            builder.append(users[i]);

            if (i != users.length - 1) {
                builder.append(",");
            }
        }

        String joined = builder.toString();
        System.out.println(joined); // Ann,John,Kate
    }
}

Output:

Ann,John,Kate

 

1 answers
2 points
Answered by:
Root-ssh
7497

It is very easy way to join a Array or List of String with commas.

Quick solution with java 8 String.join method:

// Java 8
String.join(",", users);

If we don't have java 8, we can use Guava Joiner, quick example:

// Guava Joiner
Joiner.on(",").join(users)

1. Java 8 - String.join

public class StringJoinerExample {

    public static void main(String[] args) {

        String[] users = {"Ann", "John", "Kate"};
        String join = String.join(",", users);

        System.out.println(join); // Ann,John,Kate
    }
}

Output:

Ann,John,Kate

2. Java 8 - Arrays.stream + Collectors.joining

import java.util.Arrays;
import java.util.stream.Collectors;

public class CollectorsExample {

    public static void main(String[] args) {

        String[] users = {"Ann", "John", "Kate"};
        String join = Arrays.stream(users)
                .collect(Collectors.joining(","));

        System.out.println(join); // Ann,John,Kate
    }
}

Output:

Ann,John,Kate

3. Guava Joiner

import com.google.common.base.Joiner;

public class JoinerExample {

    public static void main(String[] args) {

        String[] users = {"Ann", "John", "Kate"};
        String join = Joiner.on(",").join(users);

        System.out.println(join); // Ann,John,Kate
    }
}
Ann,John,Kate

4. Old school for loop and StringBuilder

It is the way in the question. We can use just old school for loop and StringBuilder.

0 comments Add comment
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.