• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
August 15, 2022 |2.3K Views

Java Program to Clone a List

Description
Discussion

In this video, we will write a JAVA program for cloning a List. 
Cloning refers to the creation of an exact copy of an object. It creates a new instances/objects of the class of the current object and initializes all its fields with exactly the data of the corresponding fields of this object.

Here we see 3 different methods to clone a list in a JAVA:

1) Using copy constructor: In this method, using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection.

2) Using Clist.addAll(List)/Clone: In this method, the List class has a method called addAll(), which appends all the elements of one collection to the list.

3) Using JAVA stream 8: Using the Streams API introduced in JAVA 8, cloning of a list is possible. The collect() method (along with toList() method) is used to clone a list.

Examples:
Input: list = [“I”, “Love”, “GeeksforGeeks”]
Output: clonedList = [“I”, “Love”, “GeeksforGeeks”]

Input: list = [“Welcome”, “To”,” GeeksforGeeks”]
Output: clonedList = [“Welcome”, “To”,”GeeksforGeeks”]

How to clone a list in Java:
https://www.geeksforgeeks.org/how-to-clone-a-list-in-java/