Convert an ArrayList of String to a String array in Java

Java 8Object Oriented ProgrammingProgramming

At first, let us set an ArrayList of string −

ArrayList<String> arrList = new ArrayList<String>();
arrList.add("Bentley");
arrList.add("Audi");
arrList.add("Jaguar");
arrList.add("Cadillac");

Now, use toArray() to convert to a string array −

int size = arrList.size();
String res[] = arrList.toArray(new String[size]);

Example

Following is the program to convert an ArrayList of String to a String array in Java −

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> arrList = new ArrayList<String>();
      arrList.add("Bentley");
      arrList.add("Audi");
      arrList.add("Jaguar");
      arrList.add("Cadillac");
      arrList.add("Mazda");
      arrList.add("Land Rover");
      arrList.add("Porsche");
      int size = arrList.size();
      String res[] = arrList.toArray(new String[size]);
      System.out.println("String Array...");
      for(String s: res) {
         System.out.println(s);
      }
   }
}

Output

String Array...
Bentley
Audi
Jaguar
Cadillac
Mazda
Land Rover
Porsche
raja
Published on 25-Sep-2019 08:02:17
Advertisements