Skip to main content
I found the following declaration of a map in a Trailhead example, and I'm curious, why do we specify "<Id,Account>" in the declaration? It looks to me like we're declaring a map of Opportunities, so it's not clear to me why we specify Account.

Map<Id,Account> acctsWithOpps = new Map<Id,Account>(

        [SELECT Id,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);

)
1 answer
  1. Apr 5, 2015, 5:13 AM
    Hi Alex,

    Map is the Collection of key value pair and when you initialize your map while declaring it takes Id as key and value from FROM clause, so if you have declare it FROM Account it will put Account as value, Opportunity in your syntax is coming as inner query so by default you can't put that.

    if you want to make a Map of Opportunity from your above code you need to iterate over those results and create another Map where you will initialize that as Map<id,Opportunity> and then fill that with Opportunity records.

     

    //Opportunity Map

    Map<id,Opportunity> OppMap = new Map<id,Opportunity>();

    Map<Id,Account> acctsWithOpps = new Map<Id,Account>(

            [SELECT Id,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN :Trigger.newmap.keyset()]);

    for(Account acc : acctsWithOpps.values())

    {

      //Because this is inner query for per single Account record iterate it

        for(Opportunity Opp : acc.opportunities)

        {

            OppMap.put(opp.id,Opp);

        }

    }

    Does it makes sense ?

    Thanks,

    Himanshu

    Salesforce Certified Developer | Administrator | Service Cloud Consultant

    P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
0/9000