[SalesForce] How to add values to a Map

This is my code:

If(OppLineItems.size() > 0) 
    {
        insert OppLineItems;

        for(OpportunityLineItem OppLI : OppLineItems)
        {
            Map<Account, List<OpportunityLineItem>> dealerships = new Map <Account, List<OpportunityLineItem>>();
            dealerships.put(OppLI.Dealership__c, OppLI);
            system.debug('Dealerships' + dealerships);
            List<Opportunity> OppsToCreate = new List<Opportunity>();
            Opportunity newOpp = new Opportunity();
            for(Account dealership : dealerships.keyset())
            {
                //Create new Opportunities and add fields
                newOpp.Name = ' Child Opportunity';
                newOpp.Account = dealership;
                newOpp.CloseDate = Date.today(); 
                newOpp.StageName = 'Prospecting';

                OppsToCreate.add(newOpp);
            }

            if(OppsToCreate.size() > 0)
            {
                insert OppsToCreate;
            }
        }

I want to go through each Dealership which is a lookup to account(dealership__c) on OpportunityLineItem and create a new Opportunity for all the OpportunityLineItems belonging to it.

But I don't know how to add the values in to the map. I am getting this error: Incompatible key type Id for Map> When I try to say dealerships.put(OppLI.Dealership__c, OppLI); leading me to think I am putting the incorrect key and values in here?

Best Answer

You're right, the keys and values are not compatible with your map.

Given:

Map<Account, List<OpportunityLineItem>> dealerships = new Map <Account, List<OpportunityLineItem>>();

The map is expecting you to put into it an Account key, and a List of OpportunityLineItems as a value.

However, when you do this:

dealerships.put(OppLI.Dealership__c, OppLI);

You're giving it an ID key, and a single OpportunityLineItem value.

If you want your map to store these, you need to change it to the following:

Map<Id, OpportunityLineItem> dealerships = new Map <Id, OpportunityLineItem>();

Alternatively, if the values do need to be lists of OpportunityLineItems, you need to check whether the map containsKey(OppLI.Dealership__c). If so, get(OppLI.Dealership__c) to return the existing list of OpportunityLineItems, add the OppLI to this list, and then put the updated list in the map with OppLI.Dealership__c as the key.