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?– RedDevilCommented May 16, 2019 at 7:30
-
Yes, I don't want to use query as my Map also has deleted event records.– user51241Commented May 16, 2019 at 8:07
Add a comment
|
1 Answer
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);
}
}
}
-
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! Commented May 20, 2019 at 9:18