How to use append() method of StringBuilder In Java
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 classes import java.util.ArrayList; // Main class public 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( "w3wiki" ); 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,w3wiki,!
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: