How to copy elements of one ArrayList to another List

In this article, we will discuss how to copy elements of one List to another List (ArrayList –> ArrayList) using Collections class’s utility copy() method

 

Copying from source List to destination List:

Method signature:

public static void copy(List destination, List source);

CopySourceListToDestinationList.java

package in.bench.resources.java.collection;

import java.util.ArrayList;
import java.util.Collections;

public class CopySourceListToDestinationList {

	public static void main(String[] args) {

		// creating Source ArrayList object of type String
		ArrayList<String> sourceArrayList = 
				new ArrayList<String>();

		// adding elements to ArrayList object
		sourceArrayList.add("Whatsup");
		sourceArrayList.add("Facebook");
		sourceArrayList.add("Orkut");

		System.out.println("Iterating source"
				+ " ArrayList values\n");

		// Iterating using enhanced for-loop
		for(String str : sourceArrayList){
			System.out.println(str);
		}


		// creating Destination ArrayList object of type String
		ArrayList<String> destinationArrayList = 
				new ArrayList<String>();

		// adding elements to ArrayList object
		destinationArrayList.add("dummy-value-1");
		destinationArrayList.add("dummy-value-2");
		destinationArrayList.add("dummy-value-3");
		destinationArrayList.add("Instagram");
		destinationArrayList.add("Pinterest");

		System.out.println("\n\nIterating destination"
				+ " ArrayList\n");

		// Iterating using enhanced for-loop
		for(String str : destinationArrayList){
			System.out.println(str);
		}

		// copy from source AL to destination AL
		Collections.copy(
				destinationArrayList, sourceArrayList);

		System.out.println("\n\nAfter copying elements "
				+ "from source to destination ArrayList\n");

		// Iterating using enhanced for-loop
		for(String str : destinationArrayList){
			System.out.println(str);
		}
	}
}

Output:

Iterating source ArrayList values

Whatsup
Facebook
Orkut


Iterating destination ArrayList values

dummy-value-1
dummy-value-2
dummy-value-3
Instagram
Pinterest


After copying elements from source to destination ArrayList

Whatsup
Facebook
Orkut
Instagram
Pinterest

Note: similarly, we can perform similar operation using addAll() method of Collection interface

 

References:

 

Happy Coding !!
Happy Learning !!

How to shuffle elements of ArrayList
How to swap elements of ArrayList