Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to copy a list to another list in Java?
A List of elements can be copied to another List in Java using multiple approaches. All methods create a shallow copy − the new list contains references to the same objects as the original.
Way 1: Constructor
Pass the source list to the ArrayList constructor −
List<String> copy = new ArrayList<>(list);
Way 2: addAll()
Create an empty list and use addAll() to add all elements from the source −
List<String> copy = new ArrayList<>(); copy.addAll(list);
Way 3: Collections.copy()
Use Collections.copy() to copy elements into an existing destination list. The destination list must already have enough elements (they get overwritten by index) −
Collections.copy(destList, sourceList);
Way 4: Streams (Java 8+)
Use the Stream API to collect elements into a new list −
List<String> copy = list.stream().collect(Collectors.toList());
Example
The following example demonstrates all four approaches ?
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);
// Way 1: Constructor
List<String> copy1 = new ArrayList<>(list);
System.out.println("Copy 1 (constructor): " + copy1);
// Way 2: addAll()
List<String> copy2 = new ArrayList<>();
copy2.addAll(list);
System.out.println("Copy 2 (addAll): " + copy2);
// Way 3: Collections.copy()
List<String> copy3 = Arrays.asList("Rob", "Julie", "John");
Collections.copy(copy3, list);
System.out.println("Copy 3 (Collections.copy): " + copy3);
// Way 4: Streams
List<String> copy4 = list.stream().collect(Collectors.toList());
System.out.println("Copy 4 (stream): " + copy4);
}
}
The output of the above code is ?
Source: [Zara, Mahnaz, Ayan] Copy 1 (constructor): [Zara, Mahnaz, Ayan] Copy 2 (addAll): [Zara, Mahnaz, Ayan] Copy 3 (Collections.copy): [Zara, Mahnaz, Ayan] Copy 4 (stream): [Zara, Mahnaz, Ayan]
Conclusion
The constructor approach is the simplest and most commonly used method for copying a list. All four methods create shallow copies, meaning changes to the objects inside the list will reflect in both the original and the copy.
