Convert ArrayList to Comma Separated String in Java
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 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:
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.
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.
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).
arraylist.toString() // arraylist is an object of the ArrayList class
Return Value: It returns a string representation of the ArrayList
Method 3: Using Apache Commons StringUtils class
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.
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.
Method 5: Using join() method of String class
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.