Convert ArrayList to String Array in Java
ArrayList and String Array are both used to store a group of objects. The ArrayList is a data structure used to store the group of the object, while a string array is used to store a group of strings values. Sometimes we need to convert our data structure from ArrayList to String Array. Unfortunately java.util package does not provide any direct method for this conversion. However, we can perform this conversion using some methods.
The ArrayList can be converted to String directly using the Spring Framework. Spring framework provides two very popular and well-known features, Dependency Injection and IOC container, which contains API for some common conversions like Collection to String. The ArrayList can be easily converted using Spring's StringUtils class.
In the Java collection framework, we can convert our data structure from ArrayList to String Array using the following methods:
Method1: Using ArrayList.get() method
The ArrayList.get() method is a manual way of converting all the ArrayList elements to the String Array. It copies all the elements from ArrayList<string> to String Array.
Consider the below example to implement this method:
Hello Java Tpoint
From the above example, we have copied all the ArrayList<String> elements to the String Array. We have used the size() method to obtain the ArrayList size, then fetched its element using the get() method and assigned each element to the respected array element by using the assignment (=) operator.
Method2: Using copyOf() method
The copyOf() method is used to copy the specified array with the specified length ( truncating or padding with false). To convert the ArrayList to String Array by using the copyOf() method, we will access the ArrayList, convert it to objects from the ArrayList, and then convert it to String Array.
Consider the below example to understand the implementation of this method:
ArrayList: [Hello, Java, Tpoint] String Array: [Hello, Java, Tpoint]
From the above example, we have fetched the ArrayList using the GetArrayElements function and converting it to an object using the toArray() method, then converting it to String Array using the copyOf() method.
Method3: Using toArray() method
The toArray() method is used to return an array having all the elements in the collection. Here, we are using toArray() method to convert the ArrayList to String Array.
Consider the below example to understand the implemention of this method:
Hello Java Tpoint
From the above example, we have converted ArrayList elements to the String Array. In this method, we do not need to copy each element from the array list to the array. We can fetch them all by using the toArray() method.
Hence, we can change our data structure from ArrayList to String Array using any of the above methods. All of the above methods are efficient and will work for all the Java versions. We have performed all the examples on Java version 8