In Java 8 or later:
String listString = String.join(", ", list);
In case the list is not of type String, a joining collector can be used:
String listString = list.stream().map(Object::toString)
.collect(Collectors.joining(", "));
Answer from Vitalii Fedorenko on Stack OverflowIn Java 8 or later:
String listString = String.join(", ", list);
In case the list is not of type String, a joining collector can be used:
String listString = list.stream().map(Object::toString)
.collect(Collectors.joining(", "));
If you happen to be doing this on Android, there is a nice utility for this called TextUtils which has a .join(String delimiter, Iterable) method.
List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
String joined = TextUtils.join(", ", list);
Obviously not much use outside of Android, but figured I'd add it to this thread...
What are some common issues faced when converting a list to a string in Java?
How can you remove brackets when converting a list to a string in Java?
What are the differences between hashmap and hashtable in Java?
Another idea is to use the Apache Commons Lang to write the following code:
StringUtils.join(myList);
The interest is that you also can provide a separator, for example:
StringUtils.join(myList, " ; ");
Providing you don't object to the string output following the convention:
[A, B, C]
... you can simply call the List'stoString() method to obtain your output (I'm not sure why people are advocating using a loop for this). It may also be sensible to override Car's toString() method to return a human-friendly description of the object.
However, if you wish to obtain each element as an individual String you will need to iterate over the List one element at a time.