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)

// 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:




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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Practice Tags :

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.