I am fetching a Map<String , List>
object from ehcache. I don't want to update that Map
object, rather I want to copy content of cached Map
into a temporary Map
. How can I create a copy of a Map
so that changing the value in the main Map
won't also change the value in the copy.
Asked
Active
Viewed 2,194 times
3

wattostudios
- 8,666
- 13
- 43
- 57

Mahesh
- 243
- 1
- 5
- 13
2 Answers
4
It really depends on what you want to do. If you just need a shallow copy, the answer of Paul would suffice, or do the following
Map<String, Object> fromEhcache = ...
Map<String, Object> copy = new HashMap<String, Object>(fromEhcache);
However, if you need a deep copy, i.e. you need all the objects from the map to be copied aswell, you will have to iterate over the whole map, and copy each Object individually. Plus, the Objects in the Map will have to support some sort of copy constructor.

Derk
- 86
- 4
-
+1 Good to mention deep copy - the OP should really clarify what "changing value in temporary map" means. – Paul Bellora Jun 20 '12 at 14:49
-
1+1 Please read this discussion if you want to deep clone http://stackoverflow.com/questions/665860/deep-clone-utility-recomendation – sperumal Jun 20 '12 at 14:50
1
You could created a new Map
instance and then call putAll(Map)
, passing in the original Map
. This will copy all the key-value mappings into the new instance.
If you're using Guava, you could also call Maps.newHashMap(Map)
etc. to achieve the same effect in one line.

Paul Bellora
- 54,340
- 18
- 130
- 181
-
Thanks for the reply ... I already used passing map in constructor and put all n even clone . But when I am iterating List object from map and changing the object from list it still changing the cached Map object. Can any one suggest are we have any util method like BeanUtils copyProperties which will copy map values to another map without any link. – Mahesh Jun 20 '12 at 17:28