How to add all items from a collection to an ArrayList in Java?

Given a Collection with some values, the task is to add all the items of this Collection to an ArrayList in Java.

Examples:

Input: Collection = [1, 2, 3]
Output: ArrayList = [1, 2, 3]



Input: Collection = [GFG, Geek, GeeksForGeeks]
Output: ArrayList = [GFG, Geek, GeeksForGeeks]

Approach:

  • Get the Collection whose items are to be added into the ArrayList
  • Create an ArrayList
  • Add all the items of Collection into this ArrayList using ArrayList.addAll() method
  • ArrayList with all the items of Collections have been created.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to add all items
// from a collection to an ArrayList
  
import java.io.*;
import java.util.*;
import java.util.stream.*;
  
class GFG {
  
    // Function to add all items
    // from a collection to an ArrayList
    public static <T> ArrayList<T>
    createArrayList(List<T> collection)
    {
  
        // Create an ArrayList
        ArrayList<T> list = new ArrayList<T>();
  
        // Add all the items of Collection
        // into this ArrayList
        list.addAll(collection);
  
        return list;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        List<Integer> collection1
            = Arrays.asList(1, 2, 3);
        System.out.println(
            "ArrayList with all "
            + "elements of collection "
            + collection1 + ": "
            + createArrayList(collection1));
  
        List<String> collection2
            = Arrays.asList("GFG",
                            "Geeks",
                            "GeeksForGeeks");
        System.out.println(
            "ArrayList with all"
            + " elements of collection "
            + collection2 + ": "
            + createArrayList(collection2));
    }
}

chevron_right


Output:

ArrayList with all elements of collection [1, 2, 3]: [1, 2, 3]
ArrayList with all elements of collection [GFG, Geeks, GeeksForGeeks]: [GFG, Geeks, GeeksForGeeks]

java-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.