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.
package com.javatutorialhq.tutorial; import java.util.ArrayList; import java.util.List; // Java example on how to convert arraylist to array public class ArrayListConversion { public static void main(String[] args) { List arraylist = new ArrayList(); arraylist.add("java"); arraylist.add("tutorial"); arraylist.add("array"); String[] arrayString = arraylist.toArray(new String[arraylist.size()]); for(String element : arrayString){ System.out.println(element); } } }
Sample Output:
java tutorial array
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.
package com.javatutorialhq.java.examples; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /* * Java example on how to convert arraylist to array * using for loop */ public class ArrayToArrayListExample { public static void main(String[] args) { List<String> nameList = new ArrayList<String>(); nameList.add("Juan"); nameList.add("Revlon"); nameList.add("Anthony"); nameList.add("Salvatore"); Collections.sort(nameList); String[] nameArray = new String[nameList.size()]; for(int i=0;i<nameList.size();i++){ nameArray[i] = nameList.get(i); } System.out.println(Arrays.toString(nameArray)); } }
Sample Output:
[Anthony, Juan, Revlon, Salvatore]