How to create a string from a Java ArrayList?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 10-Jan-2018 10:31:41
Advertisements