The Wayback Machine - https://web.archive.org/web/20240922213646/https://www.geeksforgeeks.org/array-to-arraylist-conversion-in-java/
Open In App

Array to ArrayList Conversion in Java

Last Updated : 08 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An Array is a collection of elements that 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 the 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




// Java program to illustrate conversion
// of an array to an ArrayList
import java.util.Arrays;
import java.util.ArrayList;
 
// Driver Class
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




// 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




// 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




// 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




// 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;
 
// Driver Class
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);
    }
     
      // Main Method
    public static void main(String[] args)
    {
        String array[] = { "ABC", "DEF", "GHI", "JKL" };
        func5(array);
    }
}


Output

[ABC, DEF, GHI, JKL]



Similar Reads

ArrayList to Array Conversion in Java : toArray() Methods
Following methods can be used for converting ArrayList to Array: Method 1: Using Object[] toArray() method Syntax: public Object[] toArray() It is specified by toArray in interface Collection and interface ListIt overrides toArray in class AbstractCollectionIt returns an array containing all of the elements in this list in the correct order. Java C
4 min read
Conversion of Array To ArrayList in Java
Following methods can be used for converting Array To ArrayList: Method 1: Using Arrays.asList() method Syntax: public static List asList(T... a) // Returns a fixed-size List as of size of given array. // Element Type of List is of same as type of array element type. // It returns an List containing all of the elements in this // array in the same
5 min read
Java.util.ArrayList.add() Method in Java
Below are the add() methods of ArrayList in Java: boolean add(Object o) : This method appends the specified element to the end of this list. Parameters: object o: The element to be appended to this list. Exception: NA // Java code to illustrate add(Object o) import java.io.*; import java.util.ArrayList; public class ArrayListDemo { public static vo
2 min read
Java.util.ArrayList.addall() method in Java
Below are the addAll() methods of ArrayList in Java: boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behavior of this operation is undefined if the specified collection is modified while the ope
4 min read
Java.util.Arraylist.indexOf() in Java
The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for. // Java code to demonstrate the working of // indexOf in ArrayList // for ArrayList functions import java.util.Arra
2 min read
Array of ArrayList in Java
We often come across 2D arrays where most of the part in the array is empty. Since space is a huge problem, we try different things to reduce the space. One such solution is to use jagged array when we know the length of each row in the array, but the problem arises when we do not specifically know the length of each of the rows. Here we use ArrayL
2 min read
Convert an ArrayList of String to a String Array in Java
In Java, as we all know ArrayList class is derived from the List interface. Here we are given an ArrayList of strings and the task is to convert the ArrayList to a string array. Illustration: Input : ArrayList = [ "Geeks", "for", "Geeks" ] Output: String[] = {"Geeks", "for", "Geeks"}Input : ArrayList = [ "Jupiter", "Saturn", "Uranus", "Neptune", "S
3 min read
Difference between length of Array and size of ArrayList in Java
Array has length property which provides the length of the Array or Array object. It is the total space allocated in memory during the initialization of the array. Array is static so when we create an array of size n then n blocks are created of array type and JVM initializes every block by default value. Let's see this in the following figure. On
2 min read
Array vs ArrayList in Java
Let us discuss the concept of the arrays and ArrayList briefly in the header to incorporate the understanding in java programs later landing onto the conclusive differences between them. As we all are aware of that arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayL
6 min read
ArrayList vs LinkedList in Java
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the difference between two classes that are implemented to
5 min read
Initialize an ArrayList in Java
ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. ArrayList inherits AbstractList class and implements List interface.ArrayList is initialized by a size
3 min read
Arraylist removeRange() in Java with examples
The removeRange() method of ArrayList in Java is used to remove all elements within the specified range from an ArrayList object. It shifts any succeeding elements to the left. This call shortens the list by (toIndex-fromIndex) elements where toIndex is the ending index and fromIndex is the starting index within which all elements are to be removed
3 min read
ArrayList get(index) Method in Java with Examples
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Syntax: get(index) Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list. Exception: It throws IndexOutOfBoundsException if the index is out of range (index=size(
2 min read
Arraylist lastIndexOf() in Java with example
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Syntax : lastIndexOf(element) Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found. Prog
2 min read
Arraylist.contains() in Java
In Java, ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Syntax of Java ArrayList contains() :public boolean contains(Object) object-element to be searched for Parameters: object- element whose presence in this list is to be tested Returns: It returns true if the specified element i
2 min read
ArrayList trimToSize() in Java with example
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not returns any value. It trims the capacity of this
1 min read
ArrayList isEmpty() in Java with example
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element. Syntax: list_name.isEmpty() Parameter: It does not accepts any parameter. Returns: It returns True if the list list_name has no elements else it returns f
2 min read
ArrayList clear() Method in Java with Examples
The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so whenever this operation has been performed all elements of the corresponding ArrayList will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimiz
2 min read
ArrayList retainAll() method in Java
The retainAll() method of ArrayList is used to remove all the array list's elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method. Syntax: public boolean retainAll(Collection C) Parameters: The
4 min read
Reverse an ArrayList in Java using ListIterator
Assuming you have gone through arraylist in java and know about arraylist. This post contains different examples for reversing an arraylist which are given below:1. By writing our own function(Using additional space): reverseArrayList() method in RevArrayList class contains logic for reversing an arraylist with integer objects. This method takes an
6 min read
ArrayList spliterator() method in Java
The spliterator() method of ArrayList returns a Spliterator of the same elements as ArrayList but created Spliterator is late-binding and fail-fast. A late-binding Spliterator binds to the source of elements. It means that Arraylist at the point of the first traversal, first split, or the first query for estimated size, rather than at the time the
3 min read
ArrayList forEach() method in Java
The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised. The operation is performed in the order of iteration if that order is specified by the method. Exceptio
2 min read
ArrayList removeIf() method in Java
The removeIf() method of ArrayList is used to remove all of the elements of this ArrayList that satisfies a given predicate filter which is passed as a parameter to the method. Errors or runtime exceptions are thrown during iteration or by the predicate are pass to the caller. This method returns True, if we are able to remove some element. Java 8
3 min read
Java Program to Convert ArrayList to LinkedList
Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5] ArrayList - An ArrayList is a part of the collect
6 min read
ArrayList iterator() method in Java with Examples
The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast. Syntax: Iterator iterator() Parameter: This method do not accept any parameter. Return Value: This method returns an iterator over the elements in this list in proper
2 min read
ArrayList ensureCapacity() method in Java with Examples
The ensureCapacity() method of java.util.ArrayList class increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. Syntax: public void ensureCapacity(int minCapacity) Parameters: This method takes the desired minimum capacity as a parameter
2 min read
ArrayList removeAll() method in Java with Examples
The removeAll() method of java.util.ArrayList class is used to remove from this list all of its elements that are contained in the specified collection. Syntax: public boolean removeAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be removed from this list. Returns Value: This method returns true if
3 min read
ArrayList listIterator() method in Java with Examples
listIterator() The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast. Syntax: public ListIterator listIterator() Return Value: This method returns a list iterator over the elements in this list (in proper sequence). Below
3 min read
ArrayList set() method in Java with Examples
The set() method of java.util.ArrayList class is used to replace the element at the specified position in this list with the specified element. Syntax: public E set(int index, E element) Parameters: This method takes the following argument as a parameter. index- index of the element to replace element- element to be stored at the specified position
2 min read
ArrayList size() method in Java with Examples
The size() method of java.util.ArrayList class is used to get the number of elements in this list. Syntax: public int size() Returns Value: This method returns the number of elements in this list. Below are the examples to illustrate the size() method. Example 1: // Java program to demonstrate // size() method // for Integer value import java.util.
2 min read