Groovy web console

subscribe to the feed Subscribe
to this
site

Deep Copy

Published 1 week ago by Maurice
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
Map<String, List<String>> myMap = new HashMap<>()

myMap['entry1'] = ['1','2','3']
myMap['entry2'] = ['4','5','6']

// This is what you do
Map<String, List<String>> myShallowCopy = new HashMap<>(myMap)

// Some random modification affecting the shallow copied objects
myShallowCopy['entry1'].clear()
myShallowCopy['entry2'].clear()

// You will see that the lists are now empty in the original
println('Original after modifying the copied map' + myMap) // Prints map[entry1:[], entry2:[]]

myMap['entry1'] = ['1','2','3']
myMap['entry2'] = ['4','5','6']

// This is what you want to do
Map<String, List<String>> myDeepCopy = myMap.collectEntries { myKey, myValue ->
  [myKey, new ArrayList<>(myValue)]
}

// Some random modification affecting the deep copied objects
myDeepCopy['entry1'].clear()
myDeepCopy['entry2'].clear()

println('Original after modifying the copied map' + myMap) // Prints map[entry1:[1, 2, 3], entry2:[4, 5, 6]]