How to Clone or Copy a List in Java
In this tutorial, we are going to see different methods used to clone or copy a list in Java.
- Using a copy builderc
- Using addAll() method
- Using clone() method
- Using streams in Java 8
Method 1: Clone or Copy a List Using a copy builder
Using the ArrayList constructor in Java, a new list can be initialized with elements from another collection.
Syntax:
ArrayList liste_clone = new ArrayList(collection c);
‘c’ is the collection containing the elements to add to ‘liste_clone’.
Example :
import java.util.*; public class Main { public static void main(String[] args) { // Create a list List<String> list = Arrays.asList("A", "B", "C", "D", "E"); // Clone the list List<String> clone_list = new ArrayList<String>(list); System.out.println(clone_list); } }
Output:
[A, B, C, D, E]
Method 2: Clone or Copy a List Using addAll() method
List class has a method called addAll(), which adds all the items in a collection to the list.
Syntax:
boolean addAll(Collection c);
‘c’ is the collection containing the elements to add to the list.
Example :
import java.util.*; public class Main { public static void main(String[] args) { // Create a list List<String> list = Arrays.asList("A", "B", "C", "D", "E"); List<String> clone_list = new ArrayList<String>(); // Clone the list clone_list.addAll(list); System.out.println(clone_list); } }
Output:
[A, B, C, D, E]
Method 3: Clone or Copy a List Using clone() method
The clone() method in Java is used to create a new instance of a class of the current object and initialize all of its fields with the contents of the specified object.
Syntax:
protected Object clone()
Example :
import java.util.*; public class Main { public static void main(String[] args) { // Create a list ArrayList<String> list = new ArrayList<String>(); // Add values to the ArrayList list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); // Clone the list Object clone_list = list.clone(); System.out.println(clone_list); } }
Output:
[A, B, C, D, E]
Method 4: Clone or Copy a List Using streams in Java 8
Using the Streams API introduced in JAVA 8, list cloning is possible. The collect() method (with toList() method) is used to clone a list.
Syntax:
Stream.collect()
Example :
import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { // Create a list List<String> list = Arrays.asList("A", "B", "C", "D", "E"); // Clone the list List<String> clone_list = list.stream().collect(Collectors.toList()); System.out.println(clone_list); } }
Output:
[A, B, C, D, E]