C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We use String.join to convert the ArrayList into a single string. We use a comma delimiter.
Result: The ArrayList's contents are now represented in a string with comma character delimiters.
Java program that converts ArrayList to string
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);
}
}
Output
cat,dog,bird
Java program that uses String.join, empty 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);
}
}
Output
abcDEFghi
SetLength: We remove the last character in the StringBuilder with a call to setLength. This eliminates the trailing ":" char.
Java program that uses StringBuilder, ArrayList
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);
}
}
Output
10:200:3000