I often encounter the task of creating a String representation of a collection of objects.
Example:
String[] collection = {"foo", "bar", "lorem", "dolar"};
The view I want to create is "foo, bar, lorem, dolar" .
Every time I come across this task, I wonder which of the most convenient ways to achieve the desired result.
I know that there are many ways to get the desired view, but for example, I always wondered if it was possible to create a string just by using the for / each loop?
So:
StringBuilder builder = new StringBuilder(); for (String tag : list) { builder.append(tag + ", "); String representation = builder.toString();
Or is it best to use an iterator, if any, directly?
The alleged list is a collection (what they do it in the JDK):
Iterator<String> it = list.iterator(); while (it.hasNext()) { sb.append(it.next()); if (!it.hasNext()) { break; } sb.append(", "); }
Of course, it would be possible to index the array using the traditional for the loop or do many other things.
Question
What is the easiest / most readable / safest way to convert a list of strings to a view that separates each element with a <comma and process the edge edge at the beginning or end (does this mean that there is no comma before the first element or after the last element)?