groovydeep-copy

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.


Solution

  • 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()
    }