List to array in Java

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)

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 + " ");
    }
}

chevron_right


Output:



Geeks for Geeks Practice

Method 2 (Using toArray)

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 + " ");
    }
}

chevron_right


Output:

Geeks for Geeks Practice

Method 3 (Using Stream)

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 + " ");
    }
}

chevron_right


Output:

Geeks for Geeks Practice

Related Articles:



My Personal Notes arrow_drop_up

Lets get started

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.