This post will discuss how to clone a list in Java. We need to construct a list containing the specified list elements in the same order as the original list.

Assume there are no mutable objects in the list, i.e., the code can perform a shallow copy.

1. Using Copy Constructor

We can use a copy constructor to clone a list, which is a special constructor for creating a new object as a copy of an existing object.

Download  Run Code

Output:

[{John, 25}, {Kim, 20}]

2. Using addAll(Collection<? extends E> c) method

List interface has the addAll() method that appends all the elements in the specified collection at the end of a list. We can use the same to copy elements from the original list to an empty list.

Download  Run Code

3. Using Java 8

We can also use streams in Java 8 and above to clone a list, as shown below:

Download  Run Code

4. Using Object.clone() method

Java Object class provides the clone() method, which can be overridden by implementing the Cloneable interface. The idea is to iterate through the list, clone each item, and add it to the cloned list. We can also use Java 8 Stream to do the same.

Download  Run Code

Output:

[{John, 25}, {Kim, 20}]

5. Using Apache Commons Lang

Several third-party libraries provide convenient classes for the Serialization and Deserialization of objects. One such class is SerializationUtils provided by Apache Commons Lang which has serialize() and deserialize() methods to serialize/deserialize an object. The serialized object holds no reference to the original object on deserialization.

SerializationUtils also provides clone() method, which is shown below:

Download Code

Output:

[{John, 25}, {Kim, 20}]

6. Using JSON

We can also convert the list to a JSON string using Google’s Gson library. Then we can convert the JSON string back to a new list object and return it.

Download Code

Output:

[{John, 25}, {Kim, 20}]

7. Using Reflection

We can also use Reflection to clone a list, as shown below:

Download  Run Code

Output:

[{John, 25}, {Kim, 20}]

That’s all about cloning a List in Java.