W3docs

Best way to convert an ArrayList to a string

To convert an ArrayList to a string in Java, you can use the join method of the String class, which allows you to join the elements of the ArrayList into a single string. Here's an example of how you might do this:

To convert an ArrayList to a string in Java, the recommended approach is using the join method of the String class. This method joins the elements into a single string with a specified delimiter. Note that String.join requires Java 8 or later.


import java.util.ArrayList;

ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("cherry");

String str = String.join(", ", list);

This produces the string "apple, banana, cherry".

You can also use a loop to concatenate the elements of an ArrayList into a single string:


import java.util.ArrayList;

StringBuilder sb = new StringBuilder();
for (String s : list) {
    if (sb.length() > 0) {
        sb.append(", ");
    }
    sb.append(s);
}
String str = sb.toString();

This approach builds the string incrementally and produces the exact same output without a trailing delimiter.

I hope this helps! Let me know if you have any other questions.