Convert List to Array in Java
The List interface provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Now here we are given a List be it any LinkedList or ArrayList of strings, our motive is to convert this list to an array of strings in java using different methods.
Methods:
- Using get() method
- Using toArray() method
- Using Stream introduced in Java 8
Method 1: Using get() method
We can use the below list method to get all elements one by one and insert them into an array.
Return Type: The element at the specified index in the list.
Syntax:
public E get(int index)
Example:
Java
import java.io.*;
import java.util.LinkedList;
import java.util.List;
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()];
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
The time complexity and space complexity of this Java code is O(n), where n is the size of the list.
Method 2: Using toArray() method
Example:
Java
import java.util.*;
public 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 = list.toArray( new String[ 0 ]);
for (String x : arr)
System.out.print(x + " " );
}
}
|
Output:
Geeks for Geeks Practice
The time complexity and space complexity of this Java code is O(n), where n is the size of the list.
Method 3: Using Stream introduced in Java8
Example:
Java
import java.util.*;
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" );
int n = list.size();
String[] arr
= list.stream().toArray(String[] :: new );
for (String x : arr)
System.out.print(x + " " );
}
}
|
Output:
Geeks for Geeks Practice
Tip: We can convert the array back to the list via asList() method.
The time complexity and space complexity of this Java code is O(n), where n is the size of the list.
Related Articles:
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...