如何在 Java 中将一个列表复制到另一个列表?

javaobject oriented programmingprogramming更新于 2024/12/31 1:16:17

可以使用多种方式将元素列表复制到另一个列表。

方法 #1

通过将另一个列表作为构造函数参数传递来创建列表。

List<String> copyOflist = new ArrayList<>(list);

创建一个列表并使用 addAll 方法添加源列表的所有元素。

方法 #2

List<String> copyOfList = new ArrayList<>();
copyOfList.addAll(list);

方法 #3

使用 Collections.copy 方法将源列表的内容复制到目标。如果有索引,现有元素将被索引覆盖。

Collections.copy(copyOfList, list);

方法 #4

使用 Streams 创建列表的副本。

List<String> copyOfList = list.stream().collect(Collectors.toList());

示例

以下示例解释了使用多种方式创建 List 对象副本 −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = Arrays.asList("Zara","Mahnaz","Ayan" );
      System.out.println("Source: " + list);
      List<String> copyOfList1 = new ArrayList<>(list);
      System.out.println("Copy 1: " + copyOfList1);
      List<String> copyOfList2 = new ArrayList<>();
      copyOfList2.addAll(list);
      System.out.println("Copy 2: " + copyOfList2);
      List<String> copyOfList3 = Arrays.asList("Rob","Julie","John" );
      Collections.copy(copyOfList3, list);
      System.out.println("Copy 3: " + copyOfList3);
      List<String> copyOfList4 = list.stream().collect(Collectors.toList());
      System.out.println("Copy 4: " + copyOfList4);
   }
}

输出

这将产生以下结果 −

Source: [Zara, Mahnaz, Ayan]
Copy 1: [Zara, Mahnaz, Ayan]
Copy 2: [Zara, Mahnaz, Ayan]
Copy 3: [Zara, Mahnaz, Ayan]
Copy 4: [Zara, Mahnaz, Ayan]

相关文章


有用资源