Java: How to deep-clone a HashSet neatly?

Paul picture Paul · Jun 26, 2014 · Viewed 9.1k times · Source

I have a HashSet of MyObject that I need to clone. If MyObject implements a copy-constructor, what is the easiest, neatest way to clone Set myObjects

Obviously I could do something like:

 Set<MyObject> myNewObjects = new Set<MyObject>(); 
 for(MyObject obj: myObjects) myNewObjects.add(new MyObject(obj));

But I'm doing this as part of a loooong copy-construcotr, and I'd really like to just be able to do it in one line like:

public myClass(MyClass toClone){
    //... 
    this.myObjects = new Set<MyObjects>(toClone.getmyObjects()); 
    //... 
}

Any suggestions?

Answer

izstas picture izstas · Jun 26, 2014

If you are using Java 8, you can do something like this:

Set<MyObject> set1 = new HashSet<>();
Set<MyObject> set2 = set1.stream().map(MyObject::new).collect(Collectors.toSet());

Keep in mind, however, that using Collectors.toSet():

There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned

Although current implementation in Java 8 Update 5 uses regular HashSet.