Friday, December 27, 2024
Google search engine
HomeLanguagesJavaArray to ArrayList Conversion in Java

Array to ArrayList Conversion in Java

An Array is a collection of elements which can be of either primitive datatypes or objects. Arrays in Java are static in nature. ArrayLists, on the other hand, can only store elements as objects. ArrayLists in Java, unlike arrays, are dynamic in nature. An ArrayList is a collection class present in java.util package that implements java.util.List interface.

An array can be converted to an ArrayList using the following methods:

  1. Using ArrayList.add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.
    Syntax: public void add(int index, E element)
    

    Parameters: This function accepts 2 mandatory parameters :

    • index – The index at which the specified element is to be inserted.
    • element – The element to be inserted.

    Returns: The method does not return any value

    Exception(s): The method throws IndexOutOfBoundsException if the index is out of range.

    Example:




    // Java program to illustrate conversion 
    // of an array to an ArrayList
      
    import java.util.Arrays;
    import java.util.ArrayList;
      
    class ArrayToArrayList {
        public static void func1(int arr[])
        {
            ArrayList<Integer> array_list = 
                    new ArrayList<Integer>();
      
            // Using add() method to add elements in array_list
            for (int i = 0; i < arr.length; i++)
                array_list.add(new Integer(arr[i]));
            System.out.print(array_list);
        }
      
        public static void main(String[] args)
        {
      
            int array[] = { 1, 2, 3, 4, 5 };
            func1(array);
        }
    }

    
    
    Output:

    [1, 2, 3, 4, 5]
    
  2. Using Arrays.asList() method of java.utils.Arrays class: This method converts the array into list and then passes the list as the parameter to initialise a new ArrayList with the list values.
    Syntax: public static List asList(T[] a)
    

    Parameters: The method accepts a mandatory parameter T[] a, where a is the array by which the list will be backed and T is the type of the array.

    Returns:The method returns a list view of the specified array.

    Example:




    // Java program to illustrate conversion
    // of an array to an ArrayList
      
    import java.util.Arrays;
    import java.util.ArrayList;
      
    class ArrayToArrayList {
        public static void func2(Integer arr[])
        {
            // Using Arrays.asList() method
            ArrayList<Integer> array_list = 
                new ArrayList<Integer>(Arrays.asList(arr));
            System.out.print(array_list);
        }
      
        public static void main(String[] args)
        {
      
            // Integer objects are used instead
            // of primitives for conversion to list
            Integer array[] = { new Integer(1),
                                new Integer(2),
                                new Integer(3),
                                new Integer(4),
                                new Integer(5) };
            func2(array);
        }
    }

    
    
    Output:

    [1, 2, 3, 4, 5]
    
  3. Using Collections.addAll() method of java.utils.Collections class: This method takes the ArrayList in which the array values are to be inserted as the first parameter; and the Array whose values are to be used as the second parameter. Then it copies the values of the Array into the ArrayList.
    Syntax: public static boolean addAll(Collection c, T.. a)
    

    Parameters: The method accepts 2 mandatory parameters :

    • c – This is the collection into which elements are to be inserted.
    • a – Array to be inserted into c, of type T

    Returns: The method returns ‘true’ if the collection changed as a result of the call, ‘false’ otherwise.

    Exception(s): The method throws

    • UnsupportedOperationException.
    • NullPointerException if the specified collection is null.
    • IllegalArgumentException if some aspect of a value in the array prevents it from being added to c.

    Example:




    // Java program to illustrate conversion 
    // of an array to an ArrayList
      
    import java.util.Collections;
    import java.util.ArrayList;
      
    class ArrayToArrayList {
        public static void func3(String arr[])
        {
            ArrayList<String> array_list = new ArrayList<String>();
      
            // Using Collections.addAll() method
            Collections.addAll(array_list, arr);
            System.out.print(array_list);
        }
      
        public static void main(String[] args)
        {
      
            String array[] = { "ABC", "DEF", "GHI", "JKL" };
            func3(array);
        }
    }

    
    
    Output:

    [ABC, DEF, GHI, JKL]
    
  4. Using Arrays.stream() method of java.utils.Arrays class: This method creates a sequential stream of the values of the array. Then with the help of collect() method and the stream, the values are copied into the ArrayList.
    Syntax: public static IntStream stream(T[] a)
    

    Parameters: The method accepts a mandatory parameter ‘a’ which is the array to be converted into stream of type T
    Returns: The method returns a stream of the specified type of the array (here it is Int).

    Explanation:
    The Arrays.stream().collect() method is used which uses java.util.stream.Collectors class to convert the stream to a list with the help of toList() method.

    Note: This method requires Java 8 or higher versions.

    Example:




    // Java program to illustrate conversion 
    // of an array to an ArrayList
      
    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.stream.Collectors;
      
    class ArrayToArrayList {
        public static void func4(String arr[])
        {
            // Using Arrays.stream.collect() method.
            ArrayList<String> array_list = (ArrayList<String>)
                        Arrays.stream(arr)
                              .collect(Collectors.toList());
            System.out.print(array_list);
        }
      
        public static void main(String[] args)
        {
      
            String array[] = { "ABC", "DEF", "GHI", "JKL" };
            func4(array);
        }
    }

    
    
    Output:

    [ABC, DEF, GHI, JKL]
    
  5. Using List.of(Elements) method of java.utils.List Interface: This method takes the array as the parameter and then creates an immutable list of the values of the array. This immutable list is then passed as the parameter to create a new ArrayList,
    Syntax: static {T} List{T} of(a)
    

    Parameters: The method accepts a mandatory parameter ‘a’ which is the array to be converted and T signifies the list’s element type(this can be omitted).
    Returns: The method returns a list containing the specified elements.
    Exception(s): The method throws a NullPointerException if the array is null.

    Note: This method requires Java 9 or higher versions.

    Example:




    // Java program to illustrate conversion 
    // of an array to an ArrayList
      
    import java.util.List;
    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.stream.Collectors;
      
    class ArrayToArrayList {
        public static void func5(String arr[])
        {
            // Using List.of() method.
            ArrayList<String> array_list = 
            new ArrayList<String>(List.of(arr));
            System.out.print(array_list);
        }
      
        public static void main(String[] args)
        {
            String array[] = { "ABC", "DEF", "GHI", "JKL" };
            func5(array);
        }
    }

    
    
    Output:

    [ABC, DEF, GHI, JKL]
    

References:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments