0

I have a Map where key is event id and value is the event, Map. These events are created on Lead object. And this Map may contain more than one event created on Lead records. My requirement is to create a new Map that includes only the most recent event per Lead without using any query.

  • You would anyways need to query database to get all event records. In that query you can easily get the latest event for lead? Is there a reason you are against query? – RedDevil May 16 '19 at 7:30
  • Yes, I don't want to use query as my Map also has deleted event records. – user51241 May 16 '19 at 8:07
1
Map<Id,Event> ObjYourMAp  = new Map<Id,Event>();
// add some values in Map 
Map <Id,Event> MapLeadEvent = new Map <Id,Event>();
for(Event objEvt : ObjYourMAp.Values())
{
    //-----------------getObjectName
    String sObjName = (objEvt.WhoId).getSObjectType().getDescribe().getName();
    if(sObjName == 'Lead')
    {
        if(MapLeadEvent != null && MapLeadEvent.containsKey(objEvt.Id) )
        {
            if(MapLeadEvent.get(objEvt.Id).CreatedDate < objEvt.CreatedDate)    
                MapLeadEvent.put(objEvt.WhoId,objEvt);
        }
        else
        {
            MapLeadEvent.put(objEvt.WhoId,objEvt);
        }
    }
}
| improve this answer | |
  • If you know your map will always contain event that were created on lead you need not to check ObjectType in loop else it might count against the limit (Heap Space and CPU Time) if data is too large! – Anshul Agrawal May 20 '19 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.