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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With