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.

5
  • 63
    Define "iterating it fully", because neither god, cthulu, nor the flying spaghetti monster could get the items out of the list without iterating over all of it in some manner. Jun 1, 2012 at 12:59
  • Without iterating? :S how can your app get the content of each element without iterating?? Jun 1, 2012 at 12:59
  • 1
    I don't want to do like - String commaSepIds = ""; for(String text : ids){ commaSepIds = commaSepIds +","+ +text;} Jun 1, 2012 at 13:01
  • 24
    Chuck Norris can do that. May 26, 2014 at 12:47
  • Even Jack Bauer too... May 8, 2017 at 12:17

13 Answers 13

498

On Android use:

android.text.TextUtils.join(",", ids);
3
  • 21
    Damn, i wish i could upvote this a few times! Helped me several times!! :) Sep 4, 2015 at 10:19
  • 3
    This answer is limited to ANDROID! Use the StringUtils answer below
    – checklist
    Aug 22, 2016 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, 2018 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(", ", ",");
2
  • It can also be like this - String csv = idList.substring(1, (idList.length() - 1)); Jun 1, 2012 at 13:11
  • It depends if you want to keep the spaces after the commas or not.
    – assylias
    Jun 1, 2012 at 13:14
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

2
  • +1 - Joiner works with an iterable or object array, and can do things like skipping nulls in the input.
    – Stephen C
    Jun 1, 2012 at 13:13
  • 8
    StringUtils.join also accepts Collection and Iterator object.
    – Somu
    Jan 29, 2013 at 6:47
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(", ", "','");
3
  • Very nice, without any third party library, clever!
    – Gaucho
    Mar 4, 2014 at 17:23
  • 8
    Only works if the strings in the list don't contain any of [,]. Oct 13, 2014 at 9:04
  • 1
    And hope that java won't change the to string of list. It's a risky way wouldn't use this in a productive system.
    – Kani
    Nov 16, 2016 at 8:45
55

The quickest way is

StringUtils.join(ids, ",");
3
  • 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 8, 2014 at 9:59
  • 2
    StringUtils for the win!
    – Dan Torrey
    Dec 10, 2014 at 17:17
  • 1
    Apache Commons Lang 3's StringUtils.join(*) methods are deprecated in favour of Apache Commons Text.
    – joninx
    Nov 15, 2017 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.

18

One Liner (pure Java)

list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", "");
3
  • 2
    what is the first replaceAll doing? why are we replacing replacing "," with "," ?
    – amitsalyan
    Jun 2, 2017 at 23:37
  • this will remove spaces from the strings themselves, so ["hello world"] will become "helloworld"
    – marmor
    Apr 26, 2018 at 8:20
  • @marmor, now it should work. Thanks
    – Pujan
    Apr 26, 2018 at 8:42
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

1
  • 1
    Please refer the package. This is android.text.TextUtils ?
    – MGM
    Mar 2, 2019 at 0:24
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.

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

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

{Any collection}.stream()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString()
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.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.