I am trying to write apex code (and I'm learning how) to roll up data from the on the Account from an object with a lookup relationship to the object.

Fields from Account: ID, DealCount__c

Fields from related object - Investment__c: Target_Company__c (ID from Account), count of records.

when I try saving it, I'm getting the error: Incompatible key type Object for Map at line 22 column 12. (between ... in code below)


trigger trgRollUpToAccount on Investment__c (after insert, after update) 
    //List to store Account IDs
    List<Id> AccountIDs = new List<Id>(); 
    //Get list of target accounts from investment__c
    for(Investment__c i: Trigger.new) 
    //query to get all investment records whose account IDs are in the list
    AggregateResult[] groupedResults = [Select count(id)DealCount, Target_Company__c from Investment__c 
                                        where  Target_Company__c in :AccountIDs Group by Target_Company__c];

    // get group of account objects to update
    Map<id,Account> accountMap = new Map<id,Account>([Select id, DealCount__c from Account where id in :AccountIds]);

    //iterate over grouped results and set the account map's data to match

    **for(AggregateResult ar: groupedResults) 

        accountMap.get(ar.get('Target_Company__c' )).DealCount__c = ar.get('DealCount');  

        //Update account objects:
        try {
            update accountMap.values();
    catch(DmlException e) {

  • ar.get('Target_Company__c') returns an object, which isn't a valid key. Try casting it to an Id.
    – zgc7009
    Mar 23, 2017 at 20:40
  • This is a good exercise for learning, but if you want to do this in a production environment I'd recommend using Andrew Fawcett's Declarative Lookup Rollup Summary Tool before trying to roll your own.
    – Derek F
    Mar 23, 2017 at 20:43

1 Answer 1


The dynamic get method returns an Object, so you have to cast it to a specific type (Id in this case):


accountMap.get(ar.get('Target_Company__c' ))


accountMap.get((Id)ar.get('Target_Company__c' ))

The longhand would look more like:

Id targetCompanyId = (Id)ar.get('Target_Company__c' );
Account targetCompany = accountMap.get(targetCompanyId);
  • 1
    beat me to the edit, and to the answer.
    – Derek F
    Mar 23, 2017 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.