Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy Map in Groovy

How can I deep copy a map of maps in Groovy? The map keys are Strings or Ints. The values are Strings, Primitive Objects or other maps, in a recursive way.

like image 452
Ayman Avatar asked Oct 31 '12 09:10

Ayman


People also ask

How do I copy a Hashmap?

Instead of iterating through all of the entries, we can use the putAll() method, which shallow-copies all of the mappings in one step: HashMap<String, Employee> shallowCopy = new HashMap<>(); shallowCopy. putAll(originalMap); We should note that put() and putAll() replace the values if there is a matching key.

How do I duplicate an object in Groovy?

clone() before calling clone() on each Cloneable property of the class. Which will create a class equivalent to the following: class Person implements Cloneable { ... public Person clone() throws CloneNotSupportedException { Person result = (Person) super. clone() result.

How do I merge two maps in groovy?

The easiest way to merge two maps in Groovy is to use + operator. This method is straightforward - it creates a new map from the left-hand-side and right-hand-side maps.


1 Answers

An easy way is this:

// standard deep copy implementation def deepcopy(orig) {      bos = new ByteArrayOutputStream()      oos = new ObjectOutputStream(bos)      oos.writeObject(orig); oos.flush()      bin = new ByteArrayInputStream(bos.toByteArray())      ois = new ObjectInputStream(bin)      return ois.readObject() } 
like image 85
Ayman Avatar answered Sep 21 '22 17:09

Ayman