Convert ArrayList to Comma Separated String in Java - GeeksforGeeks

18 Nov, 2021
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. In order to convert ArrayList to a comma-separated String, these are the approaches available in Java as listed and proposed below as follows:
Earlier before Java 8 there were only standard methods available in order for this conversion but with the introduction to the concept of Streams and Lambda, new methods do arise into play of which are all listed below:  
Using append() method of StringBuilderUsing toString() methodUsing Apache Commons StringUtils classUsing Stream APIUsing String join() method of String class
Using append() method of StringBuilder
Using toString() method
Using Apache Commons StringUtils class
Using Stream API
Using String join() method of String class
Let us discuss each of the above  methods proposed to deeper depth alongside programs to get a deep-dive understanding as follows:
StringBuilder in java represents a mutable sequence of characters. In the below example, we used StringBuilder’s append() method. The append method is used to concatenate or add a new set of characters in the last position of the existing string.
Syntax:
public StringBuilder append(char a)
Parameter: The method accepts a single parameter a which is the Char value whose string representation is to be appended.
Return Value: The method returns a string object after the append operation is performed.
Example:
Java
// Java program to Convert ArrayList to// Comma Separated String// Using append() method of StringBuilder // Importing required classesimport java.util.ArrayList; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an empty ArrayList of string type        ArrayList<String> geeklist            = new ArrayList<String>();         // Adding elements to ArrayList        // using add() method        geeklist.add("Hey");        geeklist.add("Geek");        geeklist.add("Welcome");        geeklist.add("to");        geeklist.add("geeksforgeeks");        geeklist.add("!");         StringBuilder str = new StringBuilder("");         // Traversing the ArrayList        for (String eachstring : geeklist) {             // Each element in ArrayList is appended            // followed by comma            str.append(eachstring).append(",");        }         // StringBuffer to String conversion        String commaseparatedlist = str.toString();         // Condition check to remove the last comma        if (commaseparatedlist.length() > 0)                       commaseparatedlist                = commaseparatedlist.substring(                    0, commaseparatedlist.length() - 1);         // Printing the comma separated string        System.out.println(commaseparatedlist);    }}
Hey,Geek,Welcome,to,geeksforgeeks,!
toString() is an inbuilt method that returns the value given to it in string format. The below code uses the toString() method to convert ArrayList to a String. The method returns the single string on which the replace method is applied and specified characters are replaced (in this case brackets and spaces).
Syntax:
arraylist.toString()
// arraylist is an object of the ArrayList class
Return Value: It returns a string representation of the ArrayList
Example:
Java
// Java Program to Convert ArrayList to// Comma Separated String// Using toString() method // Importing required classesimport java.util.ArrayList; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an empty ArrayList of string type        ArrayList<String> geekcourses            = new ArrayList<String>();         // Adding elements to above empty ArrayList        // using add() method        geekcourses.add("Data Structures");        geekcourses.add("Algorithms");        geekcourses.add("Operating System");        geekcourses.add("Computer Networks");        geekcourses.add("Machine Learning");        geekcourses.add("Databases");         // Note: toString() method returns the output as        // [Data Structure,Algorithms,...]        // In order to replace '[', ']' and spaces with        // empty strings to get comma separated values         String commaseparatedlist = geekcourses.toString();         commaseparatedlist            = commaseparatedlist.replace("[", "")                  .replace("]", "")                  .replace(" ", "");         // Printing the comma separated string        System.out.println(commaseparatedlist);    }}
DataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases
Apache Commons library has a StringUtils class that provides a utility function for the string. The join method is used to convert ArrayList to comma-separated strings.
Example:
Java
// Java program to Convert ArrayList to// Comma Separated String// Using Apache Commons StringUtils class // Importing required classesimport java.util.ArrayList;import org.apache.commons.collections4.CollectionUtils; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an empty ArrayList of string type        ArrayList<String> geekcourses            = new ArrayList<String>();         // Adding elements to ArrayList        // using add() method        geekcourses.add("Data Structures");        geekcourses.add("Algorithms");        geekcourses.add("Operating System");        geekcourses.add("Computer Networks");        geekcourses.add("Machine Learning");        geekcourses.add("Databases");         // Mote: join() method used returns a single string        // along with defined separator in every iteration         String commalist            = StringUtils.join(geekcourses, ",");         // Printing the comma separated string        System.out.println(commalist);    }}
Output:
OutputDataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases
Stream API was introduced in Java 8 and is used to process collections of objects. The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object.
Example
Java
// Java Program to Convert ArrayList to// Comma Separated String// Using Stream API // Importing required classesimport java.util.*;import java.util.stream.Collectors; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an empty ArrayList of string type        ArrayList<String> geeklist            = new ArrayList<String>();         // Adding elements to above ArrayList        // using add() method        geeklist.add("welcome");        geeklist.add("to");        geeklist.add("geeks");        geeklist.add("for");        geeklist.add("geeks");         // collect() method returns the result of the        // intermediate operations performed on the stream        String str = geeklist.stream().collect(            Collectors.joining(","));         // Printing the comma separated string        System.out.println(str);    }}
welcome,to,geeks,for,geeks
We can convert ArrayList to a comma-separated String using StringJoiner which is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. The join() method of the String class can be used to construct the same.
Example
Java
// Java program to Convert ArrayList to// Comma Separated String// Using String join() method // Importing required classesimport java.util.*;import java.util.stream.Collectors; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an empty ArrayList of string type        ArrayList<String> geeklist            = new ArrayList<String>();         // Adding elements to ArrayList        // using add() method        geeklist.add("welcome");        geeklist.add("to");        geeklist.add("geeks");        geeklist.add("for");        geeklist.add("geeks");         // Note: String.join() is used with a delimiter        // comma along with the list        String str = String.join(",", geeklist);         // Printing the comma separated string        System.out.println(str);    }}
welcome,to,geeks,for,geeks
solankimayank
sweetyty
Java-ArrayList
Java-Collections
Java-String-Programs
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?