Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying cached Map<String , List> object into temporary Map<String , List> object

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.

like image 980
Mahesh Avatar asked May 02 '26 22:05

Mahesh


2 Answers

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.

like image 78
Derk Avatar answered May 04 '26 12:05

Derk


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.

like image 23
Paul Bellora Avatar answered May 04 '26 12:05

Paul Bellora