The Most Sophisticated Way for Creating Comma-Separated Strings from a Collection/Array/List

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Note: This answers was good when it was written 11 years ago, but now there are far better options to do this more cleanly in a single line, both using only Java built-in classes or using a utility library. See other answers below.


Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.

The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.

The original suggestion in the question can be written even more clearly and efficiently, by taking care of the redundant trailing comma:

    StringBuilder result = new StringBuilder();
for(String string : collectionOfStrings) {
result.append(string);
result.append(",");
}
return result.length() > 0 ? result.substring(0, result.length() - 1): "";

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Note: This answers was good when it was written 11 years ago, but now there are far better options to do this more cleanly in a single line, both using only Java built-in classes or using a utility library. See other answers below.


Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.

The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.

The original suggestion in the question can be written even more clearly and efficiently, by taking care of the redundant trailing comma:

    StringBuilder result = new StringBuilder();
for(String string : collectionOfStrings) {
result.append(string);
result.append(",");
}
return result.length() > 0 ? result.substring(0, result.length() - 1): "";

Best way to convert list to comma separated string in java

Since Java 8:

String.join(",", slist);

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

How to convert comma-separated String to List?

Convert comma separated String to List

List<String> items = Arrays.asList(str.split("\\s*,\\s*"));

The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.


Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.

Convert a CollectionString into comma sepearted values

public static String getCsv(List<String> list) {
if (list == null)
return null;
StringBuilder buff = new StringBuilder();
for(int i=0; i<list.size(); i++){
String item = list[i];
if (i!=0)
buff.append(",");
buff.append(item);
}
return buff.toString();
}

Output the contents of an ArrayList as a comma-separated String

Generally speaking, relying on a toString() method to do this is an easy way to inadvertently introduce bugs later on. If you change what concrete class is providing the collection (maybe to a Set instead of a List for example), your assumption that it starts and ends with square brackets might be untrue, and your output might change without you realising it.

I'd suggest that a more appropriate solution would be to iterate over the collection of Strings and add them to a StringBuilder.

So, it might look something like:

StringBuilder stringBuilder = new StringBuilder();
for(int i=0; i<strList.size(); i++)
{
stringBuilder.append(strList.get(i));
stringBuilder.append(",");
}

// Remove the last character from the StringBuilder to avoid a trailing comma.
String commaSeparatedList = stringBuilder.substring(0, stringBuilder.length() - 1);

out.println(commaSeparatedList);

How do I create a comma delimited string from an ArrayList?

Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:

...in VB.NET:

String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String()))

...in C#

string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String")))

The only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.

EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!

String.Join(",", TargetList.ToArray())

How to convert a comma separated String to ArrayList in Java

The ArrayList returned by Arrays.asList is not java.util.ArrayList. It's java.util.Arrays.ArrayList. So you can't cast it to java.util.ArrayList.

You need to pass the list to the constructor of java.util.ArrayList class:

List<String> items = new ArrayList<String>(Arrays.asList(CommaSeparated.split("\\s*,\\s*")));

or, you can simply assign the result:

List<String> items = Arrays.asList(CommaSeparated.split("\\s*,\\s*"));

but mind you, Arrays.asList returns a fixed size list. You cannot add or remove anything into it. If you want to add or remove something, you should use the 1st version.

P.S: You should use List as reference type instead of ArrayList.



Related Topics



Leave a reply



Submit