ArrayList
, String
We often use ArrayLists
to store data in Java programs. We add strings and Integers to these collections. We can convert these lists into strings.
For an ArrayList
of Strings, we can use String.join
. But for other types like Integers, a StringBuilder
is a clearer approach. We can append and add delimiters.
String.join
Here we have an ArrayList
collection that contains String
elements. We add three simple strings to it (cat, dog and bird).
String.join
to convert the ArrayList
into a single string
. We use a comma delimiter.ArrayList
's contents are now represented in a string
with comma character delimiters.import java.util.ArrayList; public class Program { public static void main(String[] args) { // Create an ArrayList and add three strings to it. ArrayList<String> arr = new ArrayList<>(); arr.add("cat"); arr.add("dog"); arr.add("bird"); // Convert the ArrayList into a String. String res = String.join(",", arr); System.out.println(res); } }cat,dog,bird
Join
, empty delimiterSometimes we want to combine just the strings in an ArrayList
, with no delimiters between them. We use an empty string
literal as the delimiter.
import java.util.ArrayList; public class Program { public static void main(String[] args) { // Append three Strings to the ArrayList. ArrayList<String> list = new ArrayList<>(); list.add("abc"); list.add("DEF"); list.add("ghi"); // Join with an empty delimiter to concat all strings. String result = String.join("", list); System.out.println(result); } }abcDEFghi
StringBuilder
, integersFor an ArrayList
containing numbers, not strings, we can convert to a string
with a StringBuilder
. We use a for
-loop.
StringBuilder
with a call to setLength
. This eliminates the trailing ":" char
.import java.util.ArrayList; public class Program { static String convertToString(ArrayList<Integer> numbers) { StringBuilder builder = new StringBuilder(); // Append all Integers in StringBuilder to the StringBuilder. for (int number : numbers) { builder.append(number); builder.append(":"); } // Remove last delimiter with setLength. builder.setLength(builder.length() - 1); return builder.toString(); } public static void main(String[] args) { // Create an ArrayList of three ints. ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(200); numbers.add(3000); // Call conversion method. String result = convertToString(numbers); System.out.println(result); } }10:200:3000
For a simple string
ArrayList
, String.join
is the best method to use. But for more complex objects or even numbers, a StringBuilder
loop is a good option.