Can ArrayList be converted to string?

Java Convert ArrayList to StringConvert an ArrayList into a string with the String.join method. Use StringBuilder and handle ints.

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.

Approaches. 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.

Example, String.join. Here we have an ArrayList collection that contains String elements. We add three simple strings to it [cat, dog and bird].

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. ArrayListarr = 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 delimiter. Sometimes we want to combine just the strings in an ArrayList, with no delimiters between them. We use an empty string literal as the delimiter.

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. ArrayListlist = 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, integers. For an ArrayList containing numbers, not strings, we can convert to a string with a StringBuilder. We use a for-loop.

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[ArrayListnumbers] { 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. ArrayListnumbers = 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.

Video liên quan

Chủ Đề