6

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?

Paul
  • 3,318
  • 8
  • 36
  • 60

3 Answers3

15

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.

izstas
  • 5,004
  • 3
  • 42
  • 56
4

You can use Google Guava's Iterables to do something like this:

Set<MyObject> newSet = new HashSet<MyObject>(
  Iterables.transform(myObjects,new Function<MyObject, MyObject>() {
    @Override
    public MyObject apply(MyObject input) {
      return new MyObject(input);
    }
  }));

Or if you want it immutable use Guava's immutable set:

Set<MyObject> newSet = ImmutableSet.copyOf(
  Iterables.transform(myObjects,new Function<MyObject, MyObject>() {
    @Override
    public MyObject apply(MyObject input) {
      return new MyObject(input);
    }
  }));

Unfortunately it does not get any more compact than what you already have unless you can use Java 8.

Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94
0
Set<MyObject> set = new HashSet<>();
        for (MyObject value : myHash) {
            set.add(value.copy());
        }

value.copy() is the function that clones your object (you need to create a method like that and create a new object and assign the fields accordingly to make deep cloning work.).

Adib Faramarzi
  • 3,798
  • 3
  • 29
  • 44