Write a Java program to construct a set containing all elements of the specified set and in the same order as the original set. In other words, clone a set in Java. Assume there are no mutable objects in the set, and a shallow copy can be performed.

1. Copy Constructor

The simplest solution is to use a copy constructor of the Set interface for cloning a set. A copy constructor is just a special constructor for creating a new object as a copy of an existing object.

Download  Run Code

2. Using addAll() method

The Set interface provides addAll(Collection<? extends E> c) method, which appends all elements of the specified collection at the end of a set. We can use it for copying elements of the given set to an empty result set.

Download  Run Code

3. Using Java 8

We can use Java 8 Stream with Collectors to clone a set, as demonstrated below:

Download  Run Code

4. Using Object.clone() method

The idea is to iterate through the set, clone each item using the clone() method, and add the cloned item to the result set. Please note that the clone() method provided by the Object class needs to be overridden by implementing the Cloneable interface.

Download  Run Code

5. Using Apache Commons Lang

We can use Apache Commons Lang’s SerializationUtils class for Serialization and Deserialization of objects. It provides serialize() and deserialize() methods, which can be used for cloning as the serialized object holds no reference to the original object on deserialization. SerializationUtils class also provides clone() method:

Download Code

6. JSON

We can also use Google’s Gson library for cloning. The idea is to convert the set to a JSON string and then convert the JSON string back to a new Set.

Download Code

That’s all about cloning a Set in Java.