How To Convert ArrayList To Array In Java?
Introduction
The elements of an ArrayList are objects belonging to wrapper classes such as Integer, Double, Boolean, and Short. These can store primitive values of one type. In contrast, array elements are primitive types. Examples are int, double, byte, and short.
Java provides several methods to change the data type of primitives to objects and vice versa, such as autoboxing (converting primitive values to corresponding objects of wrapper classes) and unboxing (converting objects of wrappers to primitive values).
The simplest way to convert an ArrayList to an Array is to create an array of the specified size and start adding numbers sequentially.
Converting ArrayLists to Arrays in Java
Here are four different ways to convert.
1. Using The Get() Method To Manually Convert
In the previous section, we discussed declaring an array of a given size, iterating over each number, and adding it to the array. You can do that in Java by following the code below.
Code
import java.util.List; |
2. Using toArray()
To convert an ArrayList to an Array in Java, use the toArray() method in the List interface, which returns an Object array. The method will convert the list elements into the array without disrupting their order.
The following Java program converts an ArrayList to an Object[] and iterates through the array content.
Sample Code
import java.util.ArrayList; |
3. Using toArray(T[] a)
In Java, the toArray() method is used to change an ArrayList to an array whose type matches the parameter passed.
Sample Code
import java.io.*; |
4. Using Streams Api To Convert Primitive Integers To Arrays
With the streams() method and mapToInt() method, we can convert ArrayList<Integer> to an array of primitive data type int
Sample Code
import java.io.*; |