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.
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.
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.
List<String> items = Arrays. asList(commaSeparated. split(",")); That should work for you.
On Android use:
android.text.TextUtils.join(",", ids);
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(", ", ",");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With