How to convert an array to List?

Here is how you can convert an array to a list using the simple Arrays.asList() method. This is a simple generic method that takes in an array and gives it as a List of the same type as the array. See how we can do it, the easy way.

// This is where Arrays and List classes are present
import java.util.*;
class ArrayToList
    public static void main(String args[])
        // An Integer array
        Integer[] a={10,20,30,40,50,60,70,80};
        // This method takes an array and returns
        // a java.util.List object for the generic
        // type of the given array type. For example,
        // if given array is integer type, List<Integer>
        // is returned, for String type, List<String> is
        // returned.
        List<Integer> l=Arrays.asList(a);
        // You can also do it with varargs
        // List<Integer> l=Arrays.asList(10,20,30,40);
        // Get the size, call the method once
        // a good practice.
        int size=l.size();
            for(int i=0;i<size;i++)
                // Get the value sending the index

If you love this post, please to share it. Also, feel free to drop a comment for further queries and post requests. Thanks! :)

Posted by at on

Tags: Arrays, Java Utilities,