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:
The map is expecting you to put into it an
Account
key, and a List ofOpportunityLineItems
as a value.However, when you do this:
You're giving it an
ID
key, and a singleOpportunityLineItem
value.If you want your map to store these, you need to change it to the following:
Alternatively, if the values do need to be lists of
OpportunityLineItems
, you need to check whether the mapcontainsKey(OppLI.Dealership__c)
. If so,get(OppLI.Dealership__c)
to return the existing list ofOpportunityLineItems
, add theOppLI
to this list, and thenput
the updated list in the map withOppLI.Dealership__c
as the key.