Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

list

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.

like image 862
Pramod Kumar Avatar asked Jun 01 '12 12:06

Pramod Kumar


People also ask

How do I create a comma separated string from a List of strings in C#?

The standard solution to convert a List<string> to a comma-separated string in C# is using the string. Join() method. It concatenates members of the specified collection using the specified delimiter between each item.

How do you add a comma separated string to a List in Java?

Split the String into an array of Strings using the split() method. Now, convert the obtained String array to list using the asList() method of the Arrays class.

How do you add Comma Separated Values in an Arraylist in Java?

List<String> items = Arrays. asList(commaSeparated. split(",")); That should work for you.


2 Answers

On Android use:

android.text.TextUtils.join(",", ids); 
like image 87
JJD Avatar answered Sep 21 '22 11:09

JJD


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(", ", ","); 
like image 26
assylias Avatar answered Sep 20 '22 11:09

assylias