In this article, we will go through multiple ways of converting a list into an array data structure in java.
List to Array Using .get() Method
get(int index) method is used to access an element at a specific index, In this method, we will traverse on List using For loop and then will access each element using .get() method also will insert the same element in the array.
Code:
package newPackage; import java.util.*; public class BeeTechnical { public static void main(String[] args) { //Initialzing List for holding Integer type objects List<Integer> list = new ArrayList<>(); //Inserting some objects in list list.add(3); list.add(1); list.add(7); list.add(10); list.add(5); //Printing list System.out.println("List : "+list); //Initializing an array of same size as list has int[] arr = new int[list.size()]; //Loop for traversing on list for(int i=0;i<list.size();i++) { //Inserting element into array by accessing list's element //using .get() method arr[i]=list.get(i); } //Printing Array System.out.println("Array : "+Arrays.toString(arr)); } }
Output:

Conversion using toArray() method
In This method, we will use the toArray() method, Which is an in-built method of the List class in Java. For this, we have to declare the data type of our array as Object[].
Code:
package newPackage; import java.util.*; public class BeeTechnical { public static void main(String[] args) { //Initialzing List for holding Integer type objects List<Integer> list = new ArrayList<>(); //Inserting some objects in list list.add(3); list.add(1); list.add(7); list.add(10); list.add(5); //Printing list System.out.println("List : "+list); //Initializing array using List's class toArray() method Object[] arr = list.toArray(); //Printing Array System.out.println("Array : "+Arrays.toString(arr)); } }
Output:

List to Array using Stream API
Stream API in Java Introduced in Java 8, It helps us to process collections of objects. A stream is defined as the sequence of objects that supports various in-built methods.
Code:
package newPackage; import java.util.*; public class BeeTechnical { public static void main(String[] args) { //Initialzing List for holding Integer type objects List<Integer> list = new ArrayList<>(); //Inserting some objects in list list.add(3); list.add(1); list.add(7); list.add(10); list.add(5); //Printing list System.out.println("List : "+list); //Conversion by using Stream API Integer[] arr = list.stream().toArray(Integer[] ::new); //Printing Array System.out.println("Array : "+Arrays.toString(arr)); } }
Output:

Conclusion
In this article, We come to know about some methods to convert a List into an Array.