138

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'
2
  • 20
    What about String[] name = {"O'Neill"}; Commented Jul 8, 2011 at 10:25
  • please change the accepted answer to the top voted one Commented Oct 19, 2020 at 11:44

24 Answers 24

251

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Exactly! You can even define your own delimiters : StringUtils.join(names,',');
String list = "'" + StringUtils.join(names,"','") + "'"; this would give you the Single quotes needed by the SQL request.
For android : TextUtils.join(",", stringArrayOfEmails)
89

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)

Comments

68

Nice and simple: but java8 required!

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

Comments

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

1 Comment

@Bmoeller Have you tried TextUtils.join(...)? I guess one line code is even better and simpler than five ones.
32
if (name.length > 0) {
    StringBuilder nameBuilder = new StringBuilder();

    for (String n : name) {
        nameBuilder.append("'").append(n.replace("'", "\\'")).append("',");
        // can also do the following
        // nameBuilder.append("'").append(n.replace("'", "''")).append("',");
    }

    nameBuilder.deleteCharAt(nameBuilder.length() - 1);

    return nameBuilder.toString();
} else {
    return "";
}

9 Comments

Then I would have written a bunch of checks. I'm just explaining the concept, not giving the save-all example.
Again, concepts... And thanks for the down-vote. But there you go, fixed it.
thanks buddy you save my day but if you don't mind can you also give the answer of @Bart Kiers because i might get that situation and i am new to programming plz
Ohhh, why there's need to write so many source lines if you can simply use String.join(...) or TextUtils.join(...)?
@EugeneBrusov I'm going to go and guess because the answer posted in 2011 long before the release of Java 8 ;)
|
29

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

StringUtils.join(strArr,",");

Comments

9

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)

Comments

7

You could also simplify it using the Guava library:

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

1 Comment

How do I use Guava library where output is: "amit,rahul,surya"?
6

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);

Comments

5

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();
}

Comments

4

You can do this with one line of code:

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

Comments

3
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);
}

1 Comment

You probably meant substring(1), but what if array.length == 0?
2

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();
}

Comments

2

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

Comments

1

USE StringUtils.join function: E.g.

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

1 Comment

Why post an answer that has been previously posted multiple times?
1
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 );

3 Comments

Please add a description of what your code is exactly doing.
Converting String[] to comma separated string
In your answer, because right knows there is some code. Nothing more and nothing less, but its no help.
1

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.

Comments

0
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] + "\'";
    }
}

Comments

0

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 + "'";

Comments

0

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. :)

Comments

0

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

Comments

0

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();

Comments

0

Better rename name to names since its an Array.
Java 8+ solution, taking into :

String[] names = {"amit", "rahul", "surya","O'Neil"};
// For each name:
// single quote with another single quote
// & put single quotes around 
// & add comma at end 
String sql = Stream.<String>of(names)
    .reduce("", (acc,s)-> acc + "'" + s.replaceAll("'","''") + "',")
// Remove last trailing comma
sql = sql.substring(0, sql.length()-1)

Comments

-1

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();
        }

1 Comment

Please provide some context to your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.