Convert List to Array in JavaThe 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:
Using get() MethodIt 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: ![]() Using toArray() MethodIt 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: ![]() Using StreamThere 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: ![]() 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. |