How to Convert ArrayList to String array in java with Example

In this tutorial I have shared two methods of converting an ArrayList  to String array.

Method1 : Using ArrayList get() method

In this example we have converted the whole list to array in three steps
a. Obtain the ArrayList size using size() method
b. Bring each element of the list using get() method
c. Assigned each element to corresponding array element using assignment = operator.


import java.util.*;

 class ConvertArrayListToArray {
    public static void main(String args[]) {

                /*ArrayList declaration and initialization*/
  ArrayList<String> arrlist= new ArrayList<String>();
  arrlist.add("Apple");
  arrlist.add("Banana");
  arrlist.add("Mango");
  arrlist.add("Pear");

  /*ArrayList to Array Conversion */
  String array[] = new String[arrlist.size()];              
  for(int j =0;j<arrlist.size();j++){
    array[j] = arrlist.get(j);
  }

  /*Displaying Array elements*/
  for(String k: array)
  {
   System.out.println(k);
  }
  }
}  


Output

Apple
Banana
Mango
Pear

Method 2 : Using toArray() method

In this example we will convert ArrayList to String array using toArray() method.



import java.util.*;

 class ConvertArrayListToArray {
    public static void main(String args[]) {
               
                /*ArrayList declaration and initialization*/
  ArrayList<String> cities= new ArrayList<String>();
  cities.add("Boston");
  cities.add("Dallas");
  cities.add("San jose");
  cities.add("Chicago");

  /*ArrayList to Array Conversion */
  String citinames[]=cities.toArray(new String[cities.size()]);

  /*Displaying Array elements*/
  for(String k: citinames)
  {
   System.out.println(k);
  }
  }
}  


Output

Boston
Dallas
San jose
Chicago




About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry