[java] Convert String[] to comma separated string in java

i have one String[]

String[] name = {"amit", "rahul", "surya"};

i want to send name as parameter in sql query inside IN clause so how do i convert into a format

'amit','rahul','surya'

This question is related to java

The answer is


You could also simplify it using the Guava library:

String[] name = {"amit", "rahul", "surya"};
String str = "'" + Joiner.on(",").skipNulls().join(name)
    .replace(",", "','") + "'";

Extention for prior Java 8 solution

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

If you need prefix or/ and suffix for array values

 StringJoiner joiner = new StringJoiner(",");
 for (CharSequence cs: name) {
     joiner.add("'" + cs + "'");
 }
 return joiner.toString();

Or simple method concept

  public static String genInValues(String delimiter, String prefix, String suffix, String[] name) {
    StringJoiner joiner = new StringJoiner(delimiter);
    for (CharSequence cs: name) {
      joiner.add(prefix + cs + suffix);
    }
    return joiner.toString();
  }

For example

For Oracle i need "id in (1,2,3,4,5)" 
then use genInValues(",", "", "", name);
But for Postgres i need "id in (values (1),(2),(3),(4),(5))"
then use genInValues(",", "(", ")", name);

StringBuilder sb = new StringBuilder();
for (String n : name) { 
    if (sb.length() > 0) sb.append(',');
    sb.append("'").append(n).append("'");
}
return sb.toString();

Android developers are probably looking for TextUtils.join

Android docs: http://developer.android.com/reference/android/text/TextUtils.html

Code:

String[] name = {"amit", "rahul", "surya"};
TextUtils.join(",",name)

This my be helpful!!!

private static String convertArrayToString(String [] strArray) {
            StringBuilder builder = new StringBuilder();
            for(int i = 0; i<= strArray.length-1; i++) {
                if(i == strArray.length-1) {
                    builder.append("'"+strArray[i]+"'");
                }else {
                    builder.append("'"+strArray[i]+"'"+",");
                }
            }
            return builder.toString();
        }

You can do this with one line of code:

Arrays.toString(strings).replaceAll("[\\[.\\].\\s+]", "");

here is a Utility method to split an array and put your custom delimiter, using

String.replace(String,String)
Arrays.toString(Object[])

here it is :

public static String toString(String delimiter, Object[]array){
    String s = "";

    // split array
    if (array != null && array.length > 0) {
        s = Arrays.toString(array).replace("[", "").replace("]", "");
    }

    // place delimiter (notice the space in ", ")
    if(delimiter != null){
        s = s.replace(", ", delimiter);
    }

    return s;
}

change the second argument type to suite your array type


USE StringUtils.join function: E.g.

String myCsvString = StringUtils.join(myList, ",")

As tempting and "cool" as the code may appear, do not use fold or reduce on large collections of strings, as these will suffer from the string concatenation problem

String[] strings = { "foo", "bar", "baz" };
Optional<String> result = Arrays.stream(strings)
        .reduce((a, b) -> String.format("%s,%s", a, b));
System.out.println(result.get());

Instead, as per other answers, use String.join() if you already have a collection, or a StringBuilder if not.


Two lines (excluding declarations; 'finalstring' should be initially declared equal to an empty string), if you don't care a lot about vertically spacing the for() loop:

for (int i = 0; i<string_array.length; i++) {finalstring += string_array[i]+",";}
finalstring = finalstring.substring(0,finalstring.length()-1);

Two lines, you're done. :)


String[] paramIdIdList={"P001","P002","P003"};

StringBuilder builder = new StringBuilder();
            for(String paramId : paramIdIdList) {
                builder.append(paramId+",");
            }
            builder.deleteCharAt(builder.length() -1);
            String paramIds = builder.toString();
System.Out.Println(paramIds );

You can also use org.apache.commons.lang.StringUtils API to form a comma separated result from string array in Java.

StringUtils.join(strArr,",");


In java 8 for none string array and none primitive object (Long, Integer, ...)

List<Long> ids = Arrays.asList(1l, 2l,3l);
ids.stream().map(String::valueOf).collect(Collectors.joining(","))))

In java 8 for specific field of an objets array (example a car with 2 fields color and speed)

List<Car> cars= Cars.asList(car1, cars2,car3);
    cars.stream().map(Car::getColor).collect(Collectors.joining(","))))

Combine map with valueOf for none String field of an array of objects


You may also want not to spawn StringBuilder for such simple operation. Please note that I've changed name of your array from name to names for sake of content conformity:

String[] names = {"amit", "rahul", "surya"};

String namesString = "";
int delimeters = (names.size() - 1);
for (String name : names)
    namesString += (delimeters-- > 0) ? "'" + name + "'," : "'" + name + "'";

String newNameList=null;

 for(int i = name.length;i>=0;i--){
    if(newNameList==null){
        newNameList = "\'" + name[name.length - i] + "\'";
    }
    else{
        newNameList += ",\'" + name[name.length - i] + "\'";
    }
}

If you already have Spring Framework as a dependency, you could also use the very simple util method:

org.springframework.util.StringUtils.arrayToCommaDelimitedString(String[] array)

Nice and simple: but java8 required!

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

use StringBuilder and iterate over your String[], and append each String into it:

public static String convert(String[] name) { 
    StringBuilder sb = new StringBuilder();
    for (String st : name) { 
        sb.append('\'').append(st).append('\'').append(',');
    }
    if (name.length != 0) sb.deleteCharAt(sb.length()-1);
    return sb.toString();
}

String[] name = {"amit", "rahul", "surya"};


public static String arrayToString(String array[])
{
    if (array.length == 0) return "";
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.length; ++i)
    {
        sb.append(",'").append(array[i]).append("'");
    }
    return sb.substring(1);
}

i use this

public static String convertToCommaSeparated(String[] strings) {
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; strings != null && i < strings.length; i++) {
        sb.append(strings[i]);
        if (i < strings.length - 1) {
            sb.append(',');
        }
    }
    return sb.toString();
}

Either write a simple method yourself, or use one of the various utilities out there.

Personally I use apache StringUtils (StringUtils.join)

edit: in Java 8, you don't need this at all anymore:

String joined = String.join(",", name);

This would be an optimized way of doing it

StringBuilder sb = new StringBuilder();
for (String n : arr) { 
    sb.append("'").append(n).append("',");
}
if(sb.length()>0)
    sb.setLength(sbDiscrep.length()-1);
return sb.toString();