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...
java - converting elements of a list to string - Stack Overflow
arrays - Convert List<Object> to String[] in Java - Stack Overflow
String Templates. Then What?
[Java] Comparing what's in an array list to a string
How can you remove brackets when converting a list to a string in Java?
What are some common issues faced 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.
You have to loop through the list and fill your String[].
String[] array = new String[lst.size()];
int index = 0;
for (Object value : lst) {
array[index] = (String) value;
index++;
}
If the list would be of String values, List then this would be as simple as calling lst.toArray(new String[0]);
You could use toArray() to convert into an array of Objects followed by this method to convert the array of Objects into an array of Strings:
Object[] objectArray = lst.toArray();
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);