Best way to convert an ArrayList to a string

Juan Besa picture Juan Besa · Mar 1, 2009 · Viewed 1.1M times · Source

I have an ArrayList that I want to output completely as a String. Essentially I want to output it in order using the toString of each element separated by tabs. Is there any fast way to do this? You could loop through it (or remove each element) and concatenate it to a String but I think this will be very slow.

Answer

Vitalii Fedorenko picture Vitalii Fedorenko · Apr 20, 2014

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(", "));