Skip to content
Related Articles

Related Articles

Convert ArrayList to Comma Separated String in Java
  • Last Updated : 08 Dec, 2020

To convert ArrayList to comma-separated String, these are the approaches available in Java.

  1. Using append() method of StringBuilder
  2. Using toString() method
  3. Using Apache Commons StringUtils class
  4. Using Stream API
  5. Using join() method of String class

Method 1(Using append() Method of StringBuilder):  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.



Java




// Java program to Convert ArrayList to Comma Separated
// String 
  
import java.util.ArrayList;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create an ArrayList
        ArrayList<String> geeklist
            = new ArrayList<String>();
  
        // Add elements to ArrayList
        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();
  
        // By following condition you can remove the last
        // comma
        if (commaseparatedlist.length() > 0)
            commaseparatedlist
                = commaseparatedlist.substring(
                    0, commaseparatedlist.length() - 1);
  
        System.out.println(commaseparatedlist);
    }
}
Output
Hey,Geek,Welcome,to,geeksforgeeks,!

Method 2(Using toString() method): 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()

Here, arraylist is an object of the ArrayList class.

Return Value: It returns a string representation of the arraylist

Java




// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.ArrayList;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create an ArrayList
        ArrayList<String> geekcourses
            = new ArrayList<String>();
  
        // Add elements to ArrayList
        geekcourses.add("Data Structures");
        geekcourses.add("Algorithms");
        geekcourses.add("Operating System");
        geekcourses.add("Computer Networks");
        geekcourses.add("Machine Learning");
        geekcourses.add("Databases");
  
        /* 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(" ", "");
  
        System.out.println(commaseparatedlist);
    }
}
Output
DataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases

Method 3(Using Apache Commons StringUtils class): Apache Commons library has a StringUtils class that provides utility function for the string. The join method is used to convert ArrayList to comma-separated strings.

Java




// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.ArrayList;
import org.apache.commons.collections4.CollectionUtils;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create an ArrayList
        ArrayList<String> geekcourses
            = new ArrayList<String>();
  
        // Add elements to ArrayList
        geekcourses.add("Data Structures");
        geekcourses.add("Algorithms");
        geekcourses.add("Operating System");
        geekcourses.add("Computer Networks");
        geekcourses.add("Machine Learning");
        geekcourses.add("Databases");
  
        /*join method of StringUtils class is used
        which returns a single string along with defined
        separator in every iteration.*/
  
        String commalist
            = StringUtils.join(geekcourses, ",");
        System.out.println(commalist);
    }
}

Output

OutputDataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases

Method 4(Using Stream API): 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.

Java




// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.*;
import java.util.stream.Collectors;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create ArrayList of String
        ArrayList<String> geeklist
            = new ArrayList<String>();
  
        // add elements to ArrayList
        geeklist.add("welcome");
        geeklist.add("to");
        geeklist.add("geeks");
        geeklist.add("for");
        geeklist.add("geeks");
  
        // The collect method is used to return the result
        // of the intermediate operations performed on the
        // stream.
        String str = geeklist.stream().collect(
            Collectors.joining(","));
        System.out.println(str);
    }
}
Output
welcome,to,geeks,for,geeks

Method 5(Using String join() method: We can convert ArrayList to 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.

Java




// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.*;
import java.util.stream.Collectors;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create ArrayList of String
        ArrayList<String> geeklist
            = new ArrayList<String>();
  
        // add elements to ArrayList
        geeklist.add("welcome");
        geeklist.add("to");
        geeklist.add("geeks");
        geeklist.add("for");
        geeklist.add("geeks");
  
        // String.join() is used with a delimiter comma
        // along with the list.
        String str = String.join(",", geeklist);
        System.out.println(str);
    }
}
Output
welcome,to,geeks,for,geeks

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :