📜  如何将集合中的所有项目添加到Java中的 ArrayList?

📅  最后修改于: 2022-05-13 01:54:39.750000             🧑  作者: Mango

如何将集合中的所有项目添加到Java中的 ArrayList?

给定一个包含一些值的 Collection,任务是将此 Collection 的所有项目添加到Java中的 ArrayList 中。

插图:

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

方法:

  1. 获取要添加到 ArrayList 中的项的 Collection
  2. 创建一个数组列表
  3. 使用 ArrayList.addAll() 方法将 Collection 的所有项目添加到此 ArrayList 中
  4. 已创建包含 Collections 的所有项目的 ArrayList。

例子

Java
// Java Program to Add All Items from a collection
// to an ArrayList
 
// Importing required classes
import java.io.*;
import java.util.*;
import java.util.stream.*;
 
// Main class
class GFG {
 
    // Method 1
    // To add all items from a collection
    // to an ArrayList
    public static  ArrayList
    createArrayList(List collection)
    {
 
        // Creating an ArrayList
        ArrayList list = new ArrayList();
 
        // Adding all the items of Collection
        // into this ArrayList
        list.addAll(collection);
 
        return list;
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Getting array elements as list
        // and storing in a List object
        List collection1 = Arrays.asList(1, 2, 3);
 
        // Printing elements in above List object
        System.out.println("ArrayList with all "
                           + "elements of collection "
                           + collection1 + ": "
                           + createArrayList(collection1));
 
        // Again creating another List class object
        List collection2 = Arrays.asList(
            "GFG", "Geeks", "GeeksForGeeks");
 
        // Printing elements in above List object
        System.out.println("ArrayList with all"
                           + " elements of collection "
                           + collection2 + ": "
                           + createArrayList(collection2));
    }
}


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