How to Add All Items From a Collection to an ArrayList in Java?
Last Updated :
18 Nov, 2021
Given a Collection with some values, the task is to add all the items of this Collection to an ArrayList in Java.
Illustrations:
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.
Example
Java
import java.io.*;
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> ArrayList<T>
createArrayList(List<T> collection)
{
ArrayList<T> list = new ArrayList<T>();
list.addAll(collection);
return list;
}
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));
}
}
|
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]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...