How to convert Array to List in Java

In this article, we will discuss how to convert Array to List in Java. So the first question arises in your mind is why you need to do such conversion. Well! many of the time when you call to some Java code which returns Array object and you need to pass it to another method which requires List object.

Recently while I invoked a web service request, it returned an array of string. Further, I need to pass an array of string to some other service but it required a list of string object i.e List<String> object. Hence, I had to convert the array of string object to a list of string object and pass it to service.

Let us understand various methods of converting the Array into List in Java.

Manual Conversion using for loop

To convert Array into List, one of the simplest ways is to loop the array to its size and add the Array element into List using add() method. Let us demonstrate it using below code snippet.

In the above example, we used Arrays.asList() method to convert Array to List. In above code snippet, we created two lists i.e lst and lst1

List<String> lst = Arrays.asList(strArray);

The list assigned to above list is a fixed-size list backed by the original array. Hence, you cannot add a new element to above List lst . If you try to add new element using add() method you will get following exception

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at ListToArrayDemo.main(ListToArrayDemo.java:10)

To support add() operation, you can use List<String> lst1 = new ArrayList<String>(Arrays.asList(strArray)); as described in above code snippet and you can see that using add() method new element has been added to lst1 object.

Conversion using Collections.addAll() method

Using Collections.addAll() method you can convert Array into List in java. This is one of the common method to convert Array into List.

Let us demonstrate how to convert Array to List using addAll() method in Java.