Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a proper string representation of a collection [duplicate]

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.

Question

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) ?

like image 276
Jan Avatar asked Feb 10 '23 08:02

Jan


1 Answers

With Java 8, you can:

String listJoined = String.join(",", list);
like image 141
Amila Avatar answered Feb 11 '23 21:02

Amila