Clone a Set in Java

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 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. addAll() method

Set interface provides addAll(Collection<? extends E> c) method which appends all elements of the specified collection to 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. Java 8

We can use Java 8 Streams API with Collectors to clone a Set as demonstrated below:


Download   Run Code


4. Object clone() method

The idea is to iterate through the set, clone each item using clone() method and add the cloned item to 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. Apache Commons Lang

Apache Commons Lang SerializationUtils class can be used 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:





We cn 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.




1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of