How to convert an Array to a List
Posted On
Posted By admin
If you have a non primitive array type, you can use the following code to convert it to a list:
public class ArrayToListConverter { public static void main(String args[]){ Integer[] intArr = {2,4,6,8,10}; List<Integer> intList = new ArrayList<Integer>(); //Method 1 - Using for loop for(int i:intArr){ intList.add(i); } //Method 2 - Via Arrays.asList intList = Arrays.asList(intArr); // }
Method 1
Here, we are manually iterating through the elements in the list and adding them to an int array.
Method 2
Here, we are using the Arrays.asList method. This returns a list corresponding to the array passed in. Note that this method wont work if the array is of primitive type like this:
int[] intArr = {2,4,6,8,10};
If you like this post, please do let me know via the comments box below. You can also connect with me via my Facebook Page or subscribe to my Youtube channel!