I frequently come across the task to create a String representation of a collection of objects.
example:
String[] collection = {"foo", "bar", "lorem", "dolar"};
The representation I want to create: "foo, bar, lorem, dolar".
Everytime I come across this task I wonder which is the cleanest most convinient way to achieve the desired result..
I know there are a lot of ways to get the desired representation but for example I always wondered, if there is any possibility to create the string by just using the for/each loop?
like so:
StringBuilder builder = new StringBuilder();
for (String tag : list) {
builder.append(tag + ", ");
String representation = builder.toString();
// but now the String look like this: "foo, bar, lorem, dolar, " which nobody wants
Or is it best to just use the iterator if there is one, directly?
supposing list is a collection (that's how they kind of do it in the JDK):
Iterator<String> it = list.iterator();
while (it.hasNext()) {
sb.append(it.next());
if (!it.hasNext()) {
break;
}
sb.append(", ");
}
One could of course index over the array with a traditional for-loop or do many other things.
What is the easiest / best readable / safest way to convert a list of strings into the representation separating each element with a comma, and handle the edge case in the beginning or the end (meaning that there is no comma before the first element or after the last element) ?
With Java 8, you can:
String listJoined = String.join(",", list);
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