Java convert List to Array

Previous
Next

There are many ways to convert List into Array:

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 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.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog