Java convert arraylist to array

HQ ¬Ľ Java Tutorial ¬Ľ Example Source Code ¬Ľ Java Array Examples ¬Ľ Java convert arraylist to array
Java convert arraylist to array 2018-02-16T07:27:54+00:00

From my previous post, we have discussed on how to convert an array to arrayList in java. On this section it would be the other way around because we will be showing how to convert ArrayList to array in java. There might be a question on your mind, why we have to do this? Well the answer to this is very simple, as you may know there are some scenarios where the output of a java API method is in ArrayList format and our business requirements is expecting an array, thus this tutorial was made for the sole purpose of converting ArrayList to array in java programming.

It is worth to mention that even though our business requirements or desired output  an Array, we may opt to use put our  values first on a container such as ArrayList to enjoy the powerful methods on this Object such as sorting.  Moreover  the ArrayList object has dynamic contents.  We need  to have a container that support dynamic contents in merging multiple arrays, delete specific element on our collection before converting back to an array of elements. Thus the conversion from an array to ArrayList and vice versa is a must to learn.

Java convert arraylist to array – using toArray method

Supposed that we have a list of Strings of ArrayList values.  Convert the collection to an array using the toArray method of the List collection API. Moreover, use the advance for loop (for each) to print the contents of your List.

Sample Output:

Of course the conversion can be done as well in an old fashion way like iterating through the elements of an arrayList and assign each element to your array. I strongly discouraged this method because it’s a dirty way of accomplishing the business requirements.

Java convert arraylist to array – using loop

Supposed that we have a list of names as String format as ArrayList values.  Assign the names in an ArrayList and sort the names on our List. The list of names needs to be converted to Array. After the conversion to Array using for loop, validate the contents of the array using the static method toString() of Arrays class if its sorted and contains all the elements.

Sample Output:

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close