function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mohan s 37mohan s 37 

How to avoid overwriting the map values for unique key

Hi Friends,
                  I want to place multiple values for single unique key on the nested map. See below is the code.
Map<String,Map<String,Map<String,integer>>> nestedmap = new MAp<String,Map<String,Map<String,integer>>>();
   nestedmap.put('Country',new Map<String,Map<String,integer>>{'banglore'=>new Map<String,integer>{'Count'=>55}});
   nestedmap.put('Country',new Map<String,Map<String,integer>>{'banglore'=>new Map<String,integer>{'Count1'=>60}});
   nestedmap.put('Country',new Map<String,Map<String,integer>>{'Delhi'=>new Map<String,integer>{'Count2'=>45}});
  nestedmap.put('Country',new Map<String,Map<String,integer>>{'Delhi'=>new Map<String,integer>{'Count3'=>30}});
   system.debug('nestedmap: '+nestedmap);
The debug shows only last placed record into the map and it overwrites the before placed records with last one.
debug:  {Country={Delhi={Count3=45}}}.
I want to place duplicate values and later I have to use them in my code. Please suggest me how do I avoid the overwritting of duplicate values for the above map.

Thanks,
MohanS
 
Syed Insha Jawaid 2Syed Insha Jawaid 2
HI Mohan

How about creating the key for map as below :
'Country@@Delhi@@Count3' => value;

This would create a single map of type : Map<String,Integer>();

Cheers!!!
mohan s 37mohan s 37
HI Syed Insha, I know how to put key value pair in the map, for the above case there are multiple nested maps are there. so, I want the solution how to handle above case effectively using map without overwriting the values. However, thanks for your reply. Thanks, Mohan S
Syed Insha Jawaid 2Syed Insha Jawaid 2
Hi Mohan

I got your point that the map holds the last value only.So I suggest you to change the Key for your nested map.This would in turn reduce your map nesting as well.

The Key in here will be a concatenated string of your 1st map key + '@@' + 2nd Map Key + '@@' + 3rd Map Key.
This will make the combination to be unique henceforth the values will not be overriden.

So your new Map<String,Integer> would contain following values and all the values will be preserved: 
Country@@banglore@@Count ==> 55;
Country@@banglore@@Count1 ==> 60;
Country@@Delhi@@Count2 ==> 45;
Country@@Delhi@@Count3 ==> 30;

Hope I was able to explain.

Cheers!!!!!