How to create a string from a Java ArrayList?


To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.

Example

import java.util.ArrayList;

public class String_ArrayList {
   public static void main(String args[]) {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Hello");
      al.add("are");
      al.add("you");
      StringBuffer sb = new StringBuffer();
      
      for (String s : al) {
         sb.append(s);
         sb.append(" ");
      }
      String str = sb.toString();
      System.out.println(str);
   }
}

Output

Hello are you

Updated on: 30-Jul-2019

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements