Convert String[] to comma separated string in java

Convert String[] to comma separated string in java

To convert a String[] (an array of strings) to a comma-separated string in Java, you can use a loop or the String.join() method introduced in Java 8. Here are both approaches:

  1. Using a Loop:

    You can iterate through the array and concatenate its elements with commas.

    public class StringArrayToCommaSeparated { public static void main(String[] args) { String[] stringArray = {"apple", "banana", "cherry", "date"}; StringBuilder result = new StringBuilder(); for (int i = 0; i < stringArray.length; i++) { result.append(stringArray[i]); if (i < stringArray.length - 1) { result.append(", "); } } String commaSeparatedString = result.toString(); System.out.println(commaSeparatedString); } } 
  2. Using String.join() (Java 8 and later):

    Java 8 introduced the String.join() method, which simplifies the process of joining elements in a collection with a specified delimiter.

    import java.util.Arrays; import java.util.StringJoiner; public class StringArrayToCommaSeparated { public static void main(String[] args) { String[] stringArray = {"apple", "banana", "cherry", "date"}; StringJoiner joiner = new StringJoiner(", "); Arrays.stream(stringArray).forEach(joiner::add); String commaSeparatedString = joiner.toString(); System.out.println(commaSeparatedString); } } 

    In this example, we use String.join() to join the elements of the array with a comma and space delimiter.

Both of these approaches will result in a comma-separated string:

apple, banana, cherry, date 

More Tags

ecdh client-templates child-process autosuggest win32com console openstack rspec py2exe gnupg

More Java Questions

More Chemical reactions Calculators

More Trees & Forestry Calculators

More Everyday Utility Calculators

More Housing Building Calculators