Javatpoint Logo
Javatpoint Logo

Convert List to Array in Java

The List is one of the widely used collection interfaces that is used to store the ordered collection. The List interface maintains the insertion order of elements and can store duplicate values also.

In this section, we will understand how we can convert a List into an array. In Java, we mainly have three ways to convert a List into an array which are as follows:

  1. Using get() method of List
  2. Using toArray() method
  3. Using Stream in Java 8

Using get() Method

It is one of the simplest ways to convert a list into an array. In this way, we access all the list elements one by one and add them into an array.

The syntax of the get() method of the List interface is as follows:

The get() method returns the element that is located at the specified position in the list.

Let's take an example of converting a list into an array to understand how we can use the get() method of the list.

ConvertListToArrayExample1.java

Output:

Convert List to Array in Java

Using toArray() Method

It is another way of converting a list into an array. By using the toArray() method, we can easily convert a list into an array. The toArray() method returns an array having all the elements in the list. The returned array contains elements in the same sequence as the list.

The syntax of the toArray() method of the List interface is as follows:

The toArray() method either accepts an array as a parameter or no parameter, and it returns an array containing all the elements in the list.

Let's take another example of converting a list into an array to understand how we can use the toArray() method of the list.

ConvertListToArrayExample2.java

Output:

Convert List to Array in Java

Using Stream

There is one more way of converting a List into an array, i.e., by using Stream introduced in Java8.

The syntax of the toArray() method of the List interface is as follows:

The toArray() method either accepts an array as a parameter or no parameter. It returns an array containing all the elements in the list.

Let's take another example of converting a list into an array to understand how we can use the toArray() method of the list.

ConvertListToArrayExample3.java

Output:

Convert List to Array in Java

In Java, we mostly use get() and toArray() methods for converting a list into an array. The stream() method is not efficient in comparison of get() and toArray() methods.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA