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';


            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?

  • Hi nik, Take your map as Map<Id, List<OpportunityLineItem>> dealerships = new Map <Id, List<OpportunityLineItem>>(); Since you are putting id in the key and not the object.
    – Ruchi
    Aug 26, 2015 at 10:56
  • Thanks Ruchi I had tried that originally but I got this error now: Incompatible value type OpportunityLineItem for Map<Id,List<OpportunityLineItem>> even though OppLineItems is a List?
    – Nik
    Aug 26, 2015 at 10:58

2 Answers 2


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


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.


You are putting single record in map value which is expecting list


dealerships.put(OppLI.Dealership__c, new List<OpportunityLineItem>{oppLI});

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .