184
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

Now i want an output from this list as 1,2,3,4 without explicitly iterating over it.

Community
  • 1
  • 1
Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37

13 Answers13

495

On Android use:

android.text.TextUtils.join(",", ids);
JJD
  • 50,076
  • 60
  • 203
  • 339
  • 20
    Damn, i wish i could upvote this a few times! Helped me several times!! :) – nithinreddy Sep 04 '15 at 10:19
  • 3
    This answer is limited to ANDROID! Use the StringUtils answer below – checklist Aug 22 '16 at 10:40
  • 2
    TextUtils has so many hidden gems - Google should do a better job at promoting them... They also have other util classes that are awesome and not well known. – slott Mar 20 '18 at 16:19
164

With Java 8:

String csv = String.join(",", ids);

With Java 7-, there is a dirty way (note: it works only if you don't insert strings which contain ", " in your list) - obviously, List#toString will perform a loop to create idList but it does not appear in your code:

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String idList = ids.toString();
String csv = idList.substring(1, idList.length() - 1).replace(", ", ",");
assylias
  • 321,522
  • 82
  • 660
  • 783
104
import com.google.common.base.Joiner;

Joiner.on(",").join(ids);

or you can use StringUtils:

   public static String join(Object[] array,
                              char separator)

   public static String join(Iterable<?> iterator,
                              char separator)

Joins the elements of the provided array/iterable into a single String containing the provided list of elements.

http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html

Display name
  • 2,697
  • 2
  • 31
  • 49
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
65

If you want to convert list into the CSV format .........

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

// CSV format
String csv = ids.toString().replace("[", "").replace("]", "")
            .replace(", ", ",");

// CSV format surrounded by single quote 
// Useful for SQL IN QUERY

String csvWithQuote = ids.toString().replace("[", "'").replace("]", "'")
            .replace(", ", "','");
MilanPanchal
  • 2,943
  • 1
  • 19
  • 37
55

The quickest way is

StringUtils.join(ids, ",");
toesslab
  • 5,092
  • 8
  • 43
  • 62
Nodoze
  • 680
  • 5
  • 4
  • 4
    Don't forget to import `StringUtils`: `import org.apache.commons.lang3.StringUtils` commons-lang3 is a great library for String related methods. – Doron Gold Jul 08 '14 at 09:59
  • 2
    StringUtils for the win! – Dan Torrey Dec 10 '14 at 17:17
  • 1
    [Apache Commons Lang 3](https://commons.apache.org/proper/commons-lang/)'s `StringUtils.join(*)` methods are deprecated in favour of [Apache Commons Text](https://commons.apache.org/proper/commons-text/). – joninx Nov 15 '17 at 12:31
26

The following:

String joinedString = ids.toString()

will give you a comma delimited list. See docs for details.

You will need to do some post-processing to remove the square brackets, but nothing too tricky.

Dark Star1
  • 6,986
  • 16
  • 73
  • 121
Dancrumb
  • 26,597
  • 10
  • 74
  • 130
18

One Liner (pure Java)

list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", "");
Pujan
  • 3,154
  • 3
  • 38
  • 52
13

Join / concat & Split functions on ArrayList:

To Join /concat all elements of arraylist with comma (",") to String.

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String allIds = TextUtils.join(",", ids);
Log.i("Result", allIds);

To split all elements of String to arraylist with comma (",").

String allIds = "1,2,3,4";
String[] allIdsArray = TextUtils.split(allIds, ",");
ArrayList<String> idsList = new ArrayList<String>(Arrays.asList(allIdsArray));
for(String element : idsList){
    Log.i("Result", element);
}

Done

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
10

I am having ArrayList of String, which I need to convert to comma separated list, without space. The ArrayList toString() method adds square brackets, comma and space. I tried the Regular Expression method as under.

List<String> myProductList = new ArrayList<String>();
myProductList.add("sanjay");
myProductList.add("sameer");
myProductList.add("anand");
Log.d("TEST1", myProductList.toString());     // "[sanjay, sameer, anand]"
String patternString = myProductList.toString().replaceAll("[\\s\\[\\]]", "");
Log.d("TEST", patternString);                 // "sanjay,sameer,anand"

Please comment for more better efficient logic. ( The code is for Android / Java )

Thankx.

SHS
  • 1,414
  • 4
  • 26
  • 43
5

Java 8 solution if it's not a collection of strings:

{Any collection}.stream()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString()
stites
  • 4,903
  • 5
  • 32
  • 43
Dmytro Voloshyn
  • 299
  • 4
  • 6
5

You can use below code if object has attibutes under it.

String getCommonSeperatedString(List<ActionObject> actionObjects) {
    StringBuffer sb = new StringBuffer();
    for (ActionObject actionObject : actionObjects){
        sb.append(actionObject.Id).append(",");
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    return sb.toString();
}
Unihedron
  • 10,902
  • 13
  • 62
  • 72
Brijendra Verma
  • 145
  • 2
  • 5
3

If you're using Eclipse Collections (formerly GS Collections), you can use the makeString() method.

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

Assert.assertEquals("1,2,3,4", ListAdapter.adapt(ids).makeString(","));

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

Assert.assertEquals("1,2,3,4", FastList.newListWith(1, 2, 3, 4).makeString(","));

Note: I am a committer for Eclipse collections.

Donald Raab
  • 6,458
  • 2
  • 36
  • 44
Craig P. Motlin
  • 26,452
  • 17
  • 99
  • 126
0

Here is code given below to convert a List into a comma separated string without iterating List explicitly for that you have to make a list and add item in it than convert it into a comma separated string

Output of this code will be: Veeru,Nikhil,Ashish,Paritosh

instead of output of list [Veeru,Nikhil,Ashish,Paritosh]

String List_name;
List<String> myNameList = new ArrayList<String>();
myNameList.add("Veeru");
myNameList.add("Nikhil");
myNameList.add("Ashish");
myNameList.add("Paritosh");

List_name = myNameList.toString().replace("[", "")
                    .replace("]", "").replace(", ", ",");
user3652986
  • 129
  • 2
  • 5