131

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'
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
Deepak Kumar
  • 3,623
  • 9
  • 32
  • 32

24 Answers24

243

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);
Joeri Hendrickx
  • 16,947
  • 4
  • 41
  • 53
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)
Keith Entzeroth
  • 2,049
  • 1
  • 18
  • 22
66

Nice and simple: but java8 required!

String result = String.join(",", names);
PraveenKumar Lalasangi
  • 3,255
  • 1
  • 23
  • 47
Christopher Perry
  • 38,891
  • 43
  • 145
  • 187
47
StringBuilder sb = new StringBuilder();
for (String n : name) { 
    if (sb.length() > 0) sb.append(',');
    sb.append("'").append(n).append("'");
}
return sb.toString();
NPE
  • 486,780
  • 108
  • 951
  • 1,012
31
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 "";
}
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
Nico Huysamen
  • 10,217
  • 9
  • 62
  • 88
  • 10
    Then I would have written a bunch of checks. I'm just explaining the concept, not giving the save-all example. – Nico Huysamen Jul 08 '11 at 10:27
  • 3
    Again, concepts... And thanks for the down-vote. But there you go, fixed it. – Nico Huysamen Jul 08 '11 at 10:31
  • 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 – Deepak Kumar Jul 08 '11 at 10:34
  • Nico, if it was just concepts, you should have mentioned that, or have posted pseudo code instead. However, you posted code that was valid Java. Now that you have fixed your answer, I removed the down-vote (which I always do if an answer gets improved). No need to get all cranky about a down-vote: I down-vote the answer you provide, not you as a person. – Bart Kiers Jul 08 '11 at 10:34
  • @Bart Kiers - Not grumpy at all. That's why I fixed it :) Otherwise I really would not have bothered. But yes, I get your point about valid Java code, that's my bad. And so we learn. – Nico Huysamen Jul 08 '11 at 10:40
  • Strings aren't mutable. Your `replaceAll` call does nothing. Even if you did set name to the new string, it still wouldn't do anything, seeing as `\'` is the escape sequence for `'`. –  Aug 01 '13 at 19:08
  • @Obicere - Wow don't know how I missed that... Thanks for pointing it out. – Nico Huysamen Aug 02 '13 at 07:36
  • 7
    Ohhh, why there's need to write so many source lines if you can simply use `String.join(...)` or `TextUtils.join(...)`? – Eugene Brusov Oct 24 '17 at 10:56
  • 2
    @EugeneBrusov I'm going to go and guess because the answer posted in 2011 long before the release of Java 8 ;) – Nico Huysamen Apr 10 '18 at 04:50
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,",");

GROX13
  • 4,605
  • 4
  • 27
  • 41
user797649
  • 251
  • 3
  • 5
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)
NickGreen
  • 1,742
  • 16
  • 36
7

You could also simplify it using the Guava library:

String[] name = {"amit", "rahul", "surya"};
String str = "'" + Joiner.on(",").skipNulls().join(name)
    .replace(",", "','") + "'";
acvcu
  • 2,476
  • 10
  • 40
  • 56
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);
Volatile
  • 411
  • 4
  • 7
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();
}
amit
  • 175,853
  • 27
  • 231
  • 333
4

You can do this with one line of code:

Arrays.toString(strings).replaceAll("[\\[.\\].\\s+]", "");
nullbyte
  • 1,178
  • 8
  • 16
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);
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
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();
}
Sodiq
  • 316
  • 2
  • 13
1

USE StringUtils.join function: E.g.

String myCsvString = StringUtils.join(myList, ",")
General Failure
  • 2,421
  • 4
  • 23
  • 49
Manu
  • 147
  • 2
  • 12
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 );
Vinayak
  • 11
  • 1
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.

StuartLC
  • 104,537
  • 17
  • 209
  • 285
1

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

Salim Hamidi
  • 20,731
  • 1
  • 26
  • 31
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 + "'";
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. :)

Matt Campbell
  • 1,967
  • 1
  • 22
  • 34
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

Ahmed Adel Ismail
  • 2,168
  • 16
  • 23
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();
Riz
  • 368
  • 4
  • 18
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] + "\'";
    }
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
Logan
  • 2,445
  • 4
  • 36
  • 56
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)
Nice Books
  • 1,675
  • 2
  • 17
  • 21
-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();
        }