How to Convert List to Array in Java
In this post, we are going to convert List to an Array using Java code. The list is a linear data structure that is used to store data while the array is an index based data structure that stores the similar types of data.
To convert List to an array, we are using the toArray()
method of List interface that returns an array of Objects.
We are using several examples to convert the list to an array with older and new approaches like stream and method reference.
Time for an Example:
In this example, we are creating a list of fruits and printing its elements. After that, we are converting the list to an array using the toArray() method. The toArray() method returns an Array of Object elements. So, if you want to get another type of array then pass an object of that type as an argument.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args){
List<String> fruits = new ArrayList<>();
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Orange");
System.out.println(fruits);
// Conversion List to array
String[] newArray = fruits.toArray(new String[0] );
System.out.println(newArray);
for (int i = 0; i < newArray.length; i++) {
System.out.println(newArray[i]);
}
}
}
[Mango, Apple, Orange]
[Ljava.lang.String;@3764951d
Mango
Apple
Orange
Example: Java 8
If you are using Java 8 or higher version then you can use stream() method to get stream of elements and then use method reference syntax to get array of string type elements from the list.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args){
List<String> fruits = new ArrayList<>();
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Orange");
System.out.println(fruits);
// Conversion List to array
String[] newArray = fruits.stream().toArray(String[]::new);
System.out.println(newArray);
for (int i = 0; i < newArray.length; i++) {
System.out.println(newArray[i]);
}
}
}
[Mango, Apple, Orange]
[Ljava.lang.String;@3764951d
Mango
Apple
Orange
Example:
If you are using the latest Java versions then you can get an array from the list without using stream() method and directly use toArray() method.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args){
List<String> fruits = new ArrayList<>();
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Orange");
System.out.println(fruits);
// Conversion List to array
String[] newArray = fruits.toArray(String[]::new);
System.out.println(newArray);
for (int i = 0; i < newArray.length; i++) {
System.out.println(newArray[i]);
}
}
}
[Mango, Apple, Orange]
[Ljava.lang.String;@3764951d
Mango
Apple
Orange