I have a custom object (Expense__c).

I would like to insert Apex generated records in this object but before inserting I need to check whether the record that is getting generated already exist.

A record will be considered duplicate if its Type__c and Amount__c values already exist.

Here's what I have done so far

Step1 : Create a new List object from_db_exp.. This will contain all the expense__c records from db.

Step 2 : Create a new List object which will contain the generated expenses exp

Step 3 : Now I have two collections "from_db_exp" and "exp" but I dont know how to compare the records between these two collections.

List<Expense__c> exp = new List<Expense__c>();
List<Expense__c> from_db_exp = [SELECT ID,Type__c,Amount__c FROM Expense__c];

for(Integer i=0;i<100;i++)

       exp.add(new Expense__c(type__c = 'TV',Amount__c = i));


Can someone let know how to compare records between collection when the fields to be compared is not an Id ?


Sounds like you could just build a Map of types to a Set of amounts, then skip any incoming records where the type/value already exist. Something like:

Map<String,Set<Integer>> existing_records;

List<Expense__c> from_db_exp = [
        ,   Type__c
        ,   Amount__c
    FROM    Expense__c ];

for ( Expense__c e : from_db_exp ) {
    if ( existing_records.get( e.Type__c ) == null ){
        existing_records.put( e.Type__c, new Set<Integer>() );
    existing_records.get( e.Type__c ).add( e.Amount__c );

List<Expense__c> exp = new List<Expense__c>();
String type = 'TV';
Set<Integer> amounts = existing_records.get( type );
for(Integer i=0;i<100;i++)
    if ( amounts == null || amounts.contains( i ) == false ){
        // only add the new expense if the Type does not exist or if the amount does not exist for this type
        exp.add( new Expense__c( type__c = type, Amount__c = i ) );
| improve this answer | |
  • Thanks...one quick question..cant we use two "for" loops..one for loop for one collection each and allow processing only when the condition is met..just curious – Varun Jan 9 '15 at 4:01
  • Yes, you can put a for loop within a for loop. A word of caution, though: remember that the number of operations is multiplied, not added. So, given two collections of 100 elements each, iterating over one with the other is the equivalent of performing 100 operations 100 times, or 10,000 operations. This can get you into a lot of trouble with Apex LIMITS if you aren't very careful. – JDB still remembers Monica Jan 9 '15 at 17:41

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.