I have a list (List A in image) of Cases. Each case record has a field 'External Id'. I have to create a separate List such that, for all cases which has the same F-ID's, it should take the case record whose created date is the latest.

For Example L1, L2 and L3 have the same F-ID. Out of these three, L3 has the created date value which is the latest and subsequently added to the List B. Like wise should be done for the entire List A.

How can I achieve this in Apex? Is it feasible to use nested Lists to separate the case records, compare the date and add to a new list? Can't think of way to start with..

enter image description here


What you're looking for is a Map.

To do this, all you need to do is (a) sort the record list correctly and (b) create a flat map. Here's a basic version:

Case[] cases = [SELECT ExtId__c FROM Case ORDER BY CreatedDate];
Map<String, Case> latestCaseById = new Map<String, Case>();
for(Case record: cases) {
    latestCaseById.put(record.ExtId__c, record);

It really is that simple. The database took care of the initial sorting, and the map evicts the current record in a key (if any) to store the new one, effectively replacing the older case with the newer case by ExtId__c.

  • Thanks..It worked !!! Never crossed my mind that I could use Map like this.. Learning something new everyday :) – Brav May 16 '18 at 20:15
  • @BijilRavindran Glad I could help. You'll probably find that you need this "rarely", but just enough that you'll be glad you know it. – sfdcfox May 16 '18 at 20:19

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.