In this post under Java Collections, I will show with example how to copy elements from one list to another.
Below is the complete code for your reference.
Main class
1 package core.collection;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6
7 public class ListCopyDemo {
8 public static void main(String [] args) {
9 List<Integer> integerList1 = new ArrayList<>(0);
10 integerList1.add(1);
11 integerList1.add(2);
12 integerList1.add(3);
13 integerList1.add(4);
14 integerList1.add(5);
15
16 List<Integer> integerList2 = new ArrayList<>(0);
17 integerList2.add(5);
18 integerList2.add(6);
19 integerList2.add(7);
20 integerList2.add(8);
21 integerList2.add(9);
22 integerList2.add(10);
23
24 System.out.println("---------Before copy call-----------");
25 System.out.println(integerList1);
26 System.out.println(integerList2);
27
28 Collections.copy(integerList2, integerList1);
29
30 System.out.println("---------After copy call-----------");
31 System.out.println(integerList1);
32 System.out.println(integerList2);
33 }
34 }
In the above code, I have created two list of type argument “Integer” class.
The first list “integerList1” is populated with elements 1, 2, 3, 4, and 5.
The second list “integerList2” is populated with elements 5, 6, 7, 8, 9, and 10.
At line 25 and 26, I print the elements of both the list before the call to “copy” method.
At line 28, I call the static method “copy” of java “Collections” class and pass the reference to both the list as an argument.
The “copy” method copies the elements of right side list to left side list.
When copying, the elements present in source list at a particular position are copied to the same position to the destination list also. The elements already present at that particular position in
destination list are replaced. Whereas the elements that are present in the destination list, at a position after the source list size are unchanged.
The destination list size should be equal or greater then the source list size.
In this way we can copy the elements of one list to another.
Below is the output for your reference
Output
---------Before copy call-----------
[1, 2, 3, 4, 5]
[5, 6, 7, 8, 9, 10]
---------After copy call-----------
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 10]