You need to sign in to do that
Don't have an account?

How can I optimize this with maps.
I just wrote this, and it seems to work, although I haven't tested very rigorously yet.
I know there has to be a better way to do this, though...probably with maps, but I just don't see how to do it. Any suggestions would be appreciated.
- oppties comes from a trigger(trying to code for bulk)
- lineItemsWOSchedules was generated with a soql query that pulls all line items where the OpportunityId is IN :oppties and HasSchedule field is False.
It seems really inefficient to iterate through oppties and then iterate through lineItems to find the ones related to the oppty.
for(Opportunity oppty : oppties) { for(OpportunityLineItem ol : lineItemsWOSchedules) { if(ol.OpportunityId == oppty.Id) { if(null != olWSmallestDate.ServiceDate) { if(ol.ServiceDate < olWSmallestDate.ServiceDate) { olWSmallestDate = ol; } }else {olWSmallestDate = ol;} } } if(olWSmallestDate.ServiceDate.month() < System.today().month()) { oppty.adderror('The following line item has earnings scheduled before this month. Please edit the service date to reflect the earning schedule correctly. '+olWSmallestDate.PriceBookEntry.Name); } }
create a map of opportunitiy id as key..
Map<Id,Opportunity> mapOpp = new Map<Id,Opportunity>();
for(Integer i = 0; i < Trigger.new.size(); i++)
{
mapOpp.put(Trigger.new[i].Id,Trigger.new[i]);
}
for(Integer i = 0; i < listItemsWOSchedules.size(); i++)
{
if(mapOpp.containsKey(listItemsWOSchedules[i].OpportunityId))
{
remaining code
}
--------------- or-----------------
for(Integer i = 0; i < listItemsWOSchedules.size(); i++)
{
if(Trigger.newMap.containsKey(listItemsWOSchedules[i].OpportunityId))
{
remaining code
}
}
i feel second soln will be more effective though im not sure about it.