Skip to content
Related Articles

Related Articles

Improve Article

List to array in Java

  • Difficulty Level : Easy

Given a List (LinkedListor ArrayList) of strings in Java, convert it into an array of strings.

Method 1 (Simple using get())

We can use below list method to get all elements one by one and insert into an array.

// Returns the element at the specified index in the list.
public E get(int index)




// Java program to convert a List to an array
// using get() in a loop.
import java.io.*;
import java.util.List;
import java.util.LinkedList;
  
class GFG
{
    public static void main (String[] args)
    {
        List<String> list = new LinkedList<String>();
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("Practice");
  
        String[] arr = new String[list.size()];
  
        // ArrayList to Array Conversion
        for (int i =0; i < list.size(); i++)
            arr[i] = list.get(i);
  
        for (String x : arr)
            System.out.print(x + " ");
    }
}
Output:



Geeks for Geeks Practice

Method 2 (Using toArray)




// Java program to convert a List to an array
// using toArray() in a loop.
import java.util.*;
  
public class GeeksforGeeks {
    public static void main(String[] args)
    {
        List<String> list = new LinkedList<String>();
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("Practice");
  
        String[] arr = list.toArray(new String[0]);
  
        for (String x : arr)
            System.out.print(x + " ");
    }
}
Output:
Geeks for Geeks Practice

Method 3 (Using Stream)




// Java program to demonstrate conversion of 
// Set to array using stream
import java.util.*;
  
class Test {
    public static void main(String[] args)
    {
        List<String> list = new LinkedList<String>();
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("Practice");
  
        int n = list.size();
        String[] arr = list.stream().toArray(String[] ::new);
        for (String x : arr)
            System.out.print(x + " ");
    }
}
Output:
Geeks for Geeks Practice

Related Articles:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :