Java convert List to Array

In this post, we will see how to convert List to Array in java.

There are many ways to convert List to Array in java

Using toArray() method

We can use toArray() method to convert List to String. We can either pass a array of size as List’s length or we can pass empty array.
This returns an array containing all the elements of the list in correct order.
There two overloaded methods for toArray().
Syntax:

Where,T represents generic.

Example:

OUTPUT:

Elements of list are:
[Hello, I, Am, John] Elements of Array are:
Hello
I
Am
John

Please note that if you do not pass any parameter to toArray() method, it will give us Object array.

Using Java 8’s Stream

We can simply use java 8‘ stream’s toArray() method to convert List to array.

Output:

Elements of list are:
[John, Martin, Mary, Andrew] Elements of Array are:
John
Martin
Mary
Andrew

Using Arrays.copyOf

We can use Arrays.copyOf() method also to convert List to Array. We need to use toArray() method and pass it to Arrays.copyOf() method to convert it to specified type

Output:

Elements of list are:
[John, Martin, Mary, Andrew] Elements of Array are:
John
Martin
Mary
Andrew

Using System.arraycopy

We can use System.arraycopy() method which copies an specified array, starting at the specified position, to the specified position of the target array.

Output:

Elements of list are:
[India, China, Nepal, Bhutan] Elements of Array are:
India
China
Nepal
Bhutan

Manual method

This method use loop and run it until the size of list and one by one get elements from list and add it to Array.

Example:

OUTPUT:

Elements of list are:[800, 600, 400, 200] Elements of Array are:
800
600
400
200

That’s all about converting List to Array in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *