2

I'm trying to put my AggregateResult in a map so that I can reference it later in my code.

trigger NoOfLiveProducts on Account (after insert, after Delete, after update) {

    map<Id,Integer> count1 = new Map<Id,Integer>();

    AggregateResult[] curProdCount = [SELECT AccountId, COUNT(CloseDate) date1 FROM Opportunity
                                       WHERE AccountId IN :Trigger.new
                                    GROUP BY AccountId];
    AggregateResult[] liveMktplcCount = [SELECT AccountId, COUNT(CloseDate) date2 FROM Opportunity
                                          WHERE AccountId IN :Trigger.new
                                       GROUP BY AccountId];

    for(AggregateResult ar : curProdCount){
        count1.put((Id)ar.get('Id'), Integer(ar.get('date1')));
    }



}

But there's an error at line count1.put((Id)ar.get('Id'), Integer(ar.get('date1')));

Method does not exist or incorrect signature: Integer(Object)

How can I add the Count to my map?

3
  • 1
    If you're willing to keep the entire "list" in memory, a slightly faster shortcut goes like this: Map<Id, AggregateResult> results = new Map<Id, AggregateResult>([SELECT AccountId Id, COUNT(CloseDate) date1 FROM Opportunity WHERE AccountId IN :Trigger.new GROUP BY AccountId]); This keeps you from having to iterate the results manually at some small expense of heap. – sfdcfox Jul 6 '15 at 22:25
  • @sfdcfox That sounds good to me. – Alex S Jul 6 '15 at 22:27
  • 1
    The "shortcut" only works if you alias one of your groupings by "Id" (case sensitive). It's a particularly useful construct if you can find a place to use it, but I've never seen in a manual anywhere, which is probably why more people don't use it. – sfdcfox Jul 6 '15 at 22:34
4

Cast it to an Integer instead, just like you do with Id:

count1.put((Id)ar.get('AccountId'), (Integer)ar.get('date1'));
3
  • @AlexS Also, your AccountId isn't aliased, so make sure you fix that as well. – sfdcfox Jul 6 '15 at 22:23
  • @sfdcfox But you don't need to alias grouped fields? However I'm not sure what the value of ar.get('Id') would be...maybe the map key should be AccountId. – Adrian Larson Jul 6 '15 at 22:24
  • @sfdcfox Thanks so I just need to use SELECT AccountId acctId1? – Alex S Jul 6 '15 at 22:24

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.