I'm having a custom object say obj.In my apex class I'm having two lists of this object

In list<obj__c> list1 ---- I'll be getting say suppose 3 Records &
In list<obj__c> list2 ---- I'll be getting say suppose 2 Records(this 2 records are of list1 records and will not be greater than list1).

My requirement here is I want to insert the 3rd record which is not present in list2. Every Record consists of unique Name.What would be the best way to solve this.Any help on this pls

My approach is something like this

if(list1.size() > list2.size()){
    //map my name

2 Answers 2


If I understand you correctly, you want to check if values exists in lists,

Since you have a unique name, it's best to leverage that uniqueness in combination with a map, you start of by adding all the values in your lists to 2 maps.

Map<String, Obj__c> objMap1 = new Map<String, Obj__c>();
Map<String, Obj__c> objMap2 = new Map<String, Obj__c>();

// List 1
for(Obj__c o : list1)
    objMap1.put(o.UniqueName__c, o);

// List 2
for(Obj__c o : list2)
    objMap2.put(o.UniqueName__c, o);

// Now you can easily check if that value is in your map by doing.
// or

// ... do your logic

Here is the documentation for Maps and Sets try to use this as much as possible to reduce the number of script statements you have for manually looping over lists just to check if values exists or not.

  • for(integer re=0;re<recs.size();re++){if(!recheckmap.containskey(recs[re].name)){insert recs;}}.But here I shouldn't insert recs in a for loop as it has a exception.How should I overcome this?
    – Eagerin Sf
    Mar 29, 2013 at 7:16
  • Try not to use Java/C/Javascript type of Iteration For Loops, use the enhanced For Loops and compare using Map
    – compski
    Dec 14, 2020 at 6:29

The maps seems a little unnecessary here; I would leverage Sets instead.

Set<Obj__c> set1 = new Set<Obj__c>(list1);
Set<Obj__c> set2 = new Set<Obj__c>(list2);

for(Obj__c o : set1){
     if(!set2.contains(o) ){
          //your logic
  • The problem you have with sets is, how will you define if an object is comparable to another, you can't override the equals and/or hashcode function of an SObject, and since @EagerIn_sf uses his unique string to compare, you're stuck here. This is obviously possible with classes you create in apex but not with sobjects.
    – pjcarly
    Mar 22, 2013 at 16:10
  • Ahhhhh yes, that was definitely an oversight on my part. In that case, your Map solution sounds like the best option. I'd upvote it, but I don't have enough rep yet :( lol Mar 22, 2013 at 16:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .