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 + " "); } } |
chevron_right
filter_none
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 + " "); } } |
chevron_right
filter_none
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 + " "); } } |
chevron_right
filter_none
Output:
Geeks for Geeks Practice
Related Articles:
Recommended Posts:
- Program to convert Array to List in Java
- Program to convert List of String to List of Integer in Java
- Program to convert List of Integer to List of String in Java
- Set to List in Java
- Min and Max in a List in Java
- List to Set in Java
- Immutable List in Java
- Initializing a List in Java
- List of all Java Keywords
- Convert List to Set in Java
- How to Clone a List in Java?
- Convert an Iterator to a List in Java
- Program to Convert List to Map in Java
- List get() method in Java with Examples
- How to remove a SubList from a List in Java
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.



