[SalesForce] getting ‘ Incompatible value type Object for Map’ error

I need to populate values in map<id, list<object_B__c>>(). I am getting an error when I attempt to do this. I was able to get code to compile but the problem is the way it's compiled, each iteration of my for loop creates a new list instead of a new list value. Intuitively, what makes sense doesn't seem to compile and I'm not sure why. Any insight as to why my code won't compile as well an a workaround is greatly appreciated.

This code compiles but creates a new list with each iteration of the loop:

Map<string, object_A__c> myAMap = new map<string, object_A__c>()
for(object_A__c objA: [SELECT  field_A__c, field_B__c from object_A__c]){
      myAMap.put(objA.field_A__c, objA); 

}
system.debug('***** myAMap  ' + myAMap);

map<id,list<object_B__c>> results = new map<id,list<object_B__c>>();

for(object_B__c objB: [SELECT id, field_A__c, field_B__c from object_B__c]){
  if(myAMap.containsKey(objB.field_A__c)){
    results.put(id, new list<object_B__c> {objB} );
  }
}

This is what I'm trying to do but can't compile:

The error: Incompatible value type Object for Map<id,list<object_B__c>>

   Map<string, object_A__c> myAMap = new map<string, object_A__c>()
   for(object_A__c objA: [SELECT  field_A__c, field_B__c from object_A__c]){
      myAMap.put(objA.field_A__c, objA); 
   }
   system.debug('***** myAMap  ' + myAMap);

   list<object_B__c> myList = new list<object_B__c>();
   map<id,list<object_B__c>> results = new map<id,list<object_B__c>>();

   for(object_B__c objB: [SELECT id, field_A__c, field_B__c from object_B__c]){
     if(myAMap.containsKey(objB.field_A__c)){
       results.put(id, myList.add(objB) ); // This line has the error.
     }
   }

Best Answer

The add method on List returns void, which is why you are getting an error on this line:

results.put(id, myList.add(objB) ); 

What is happening is myList.add(objB) is being executed first and nothing is returned so what actually gets put into your map is void, shown below. Hence the "Incompatible value" error.

results.put(id, void); 

You need to add to the List before putting it into the Map. The example below gets the List from the Map, makes sure the List is instantiated and then puts it back into the Map

myList = results.get(key);
if (myList == null) {
    myList = new List<object_B__c>();
}
myList.add(objB); 
results.put(id, myList);