cole cole - 1 month ago 21
Java Question

Deep copying a Java Map with values that are Sets

I have a map (

Map<String, Set<String>>
), and want to copy the map to a new map object. However, if I just feed the map to the say
HashMap
constructor (
new HashMap<String, Set<String>>(oldMap)
) it won't do a full copy, and only copies the reference to the set, which can be modified and those changes will be reflected in the new map.

Is there a more simply way of doing a full copy other than iterating over each key/value pair and creating a new
HashSet
for each set then adding that to the map?

Answer Source

There was some discussion on this here for deep cloning:

Java HashMap - deep copy

It's hard in this situation though as the new map and set need to rebuild themselves. Do you also need to clone the contents of the Set? If so then you could just serialize then de-serialize the whole collection.

Iterating yourself will almost certainly be faster and will let you control how deep the cloning goes. Serializing will be slower but so long as everything in the object tree is serializable it will copy everything in the object tree and maintain things like circular references etc. (For example if you had 2 keys in the map pointing to the same Set object then iterating will split that into 2 sets, serializing will maintain the link).