[java] How to convert a List<String> into a comma separated string without iterating List explicitly

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.

This question is related to java list

The answer is


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

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.


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.


On Android use:

android.text.TextUtils.join(",", ids);

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

{Any collection}.stream()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString()

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


One Liner (pure Java)

list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", "");

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.


The quickest way is

StringUtils.join(ids, ",");

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


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

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

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