Friday, March 29, 2019

Convert an ArrayList of String to a String array in Java

Given an ArrayList of String, the task is to convert the ArrayList to String array in java.
Examples:
Input: ArrayList = [ "Geeks", "for", "Geeks" ]
Output: String[] = {"Geeks", "for", "Geeks"}

Input: ArrayList = [ "Jupiter", "Saturn", "Uranus", "Neptune", "Sun"]
Output: String[] = {"Jupiter", "Saturn", "Uranus", "Neptune", "Sun"}
  1. Using ArrayList.get() Method
    Syntax:
     str[j] = a1.get(j)
    Approach:
    1. Get the ArrayList of Strings.
    2. Find the size of ArrayList using size() method, and Create a String Array of this size.
    3. Fetch each element of the ArrayList one by one using get() method.
    4. Assigned each element into String Array using assignment(=) operator.
    5. Print String Array.
    Below is the implementation of the above approach:// Java program to Convert ArrayList to 
    // String ArrayList using get() method 

    import java.util.*; 

    public class GFG { 

    // Function to convert ArrayList<String> to String[] 
    public static String[] GetStringArray(ArrayList<String> arr) 

    // declaration and initialise String Array 
    String str[] = new String[arr.size()]; 

    // ArrayList to Array Conversion 
    for (int j = 0; j < arr.size(); j++) { 

    // Assign each value to String array 
    str[j] = arr.get(j); 

    return str; 

    // Driver code 
    public static void main(String[] args) 

    // declaration and initialise ArrayList 
    ArrayList<String> 
    a1 = new ArrayList<String>(); 

    a1.add("Geeks"); 
    a1.add("for"); 
    a1.add("Geeks"); 

    // print ArrayList 
    System.out.println("ArrayList: " + a1); 

    // Get String Array 
    String[] str = GetStringArray(a1); 

    // Print Array elements 
    System.out.print("String Array[]: "
    + Arrays.toString(str)); 
  2. Output:
    ArrayList: [Geeks, for, Geeks]
    String Array[]: [Geeks, for, Geeks]
    
  3. Using Object array as intermediate
    Syntax:
    Object[] arr = a1.toArray()
    String str = (String)obj;
    
    Approach:
    1. Get the ArrayList of String.
    2. Convert ArrayList to Object array using toArray() method.
    3. Iterate and convert each element to desired type using typecasting. Here it is converted to String type and added to the String Array.
    4. Print String Array.

No comments:

Post a Comment