Friday, May 16, 2014

Array to List and List to Array in Java

While testing web applications we came across many list of elements or an element with list of data. In such cases we may need the following conversation instead of iterating over an array or a list.
 
Please refer the below simple example to convert a string array to a list and vice versa. But be careful about the order of elements, If required you may use collection methods to do so.

Lets take an arry of strings as below
String[] elementsAsArray = new String[]{"ele1","ele2","ele3"};

Array to List:
List arrayAsList = Arrays.asList(elementsAsArray);

List to Array:
String[] listAsArray = arrayAsList.toArray(new String[arrayAsList.size()]);