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
Yoshinori MoriYoshinori Mori 

Map

I have a fundamental question regarding Mapping.

I would like to do objMap.put as below.

Within the for loop

I don't understand why I can't use "objMap.put" instead of obj.put

There is  no error if I use "obj.put (obj.somithing_r.relation__c, obj);"

 

for(Data__c obj : dataset) {
    objMap.put(obj.somithing_r.relation__c, obj);
 } 

(Example)

public List<CityNameMast__c>cityname =  new List<CityNameMast__c>();  
public List<Data__c> dataset = new List<Data__c> ();  
dataset = DBAccess.getdata(); 
 Map<String, List<Data__c>> objMap = new Map<String, List<Data__c>>();
 for(Data__c obj : dataset) {
    objMap.put(obj.somithing_r.relation__c, obj);
 } 
 for(CityNameMast__c x: cityname) { 
   if(objMap.containsKey(x.cityname__c)) { 
   objMap.add(x.MiddleAreaName__c);
 } else {
 }

 

Mori

bob_buzzardbob_buzzard

You have a disconnect here, in that each entry is your map is an id/list pair, but you are trying to put an id/sobject pair.

 

You'll need to retrieve the list from the map based on the relation__c value, and add your object to the end of the list (creating it if it doesn't exist).  I'd also suggest you key your map by id rather than String. The reason it works on obj is that sobjects have a get/set notation to allow fields to be extracted/written to, this isn't related to your issue.

 

Try the following:

 

 

public List<CityNameMast__c>cityname =  new List<CityNameMast__c>();  
public List<Data__c> dataset = new List<Data__c> ();  
dataset = DBAccess.getdata(); 
 Map<Id, List<Data__c>> objMap = new Map<Id, List<Data__c>>();
 for(Data__c obj : dataset) 
 {
    List<Data__c> theData=objMap.get(obj.somiething__r.relation__c);
    if (null==theData)
    {
       theData=new List<Data__c>();
       objMap.put(obj.somiething__r.relation__c, theData);
    }
    theData.add(obj);
 } 

 

Your final piece of code is confusing me:

 

 

 for(CityNameMast__c x: cityname) 
 { 
   if(objMap.containsKey(x.cityname__c)) 
   { 
      objMap.add(x.MiddleAreaName__c);
   } 
   else 
   {
   }
}

There is no add method on a map.