function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
basha skbasha sk 

How to avoid duplicate Insertions ?

Map<String,String> Selected = new Map<String,String>();
Map<String,String> customvalues = new Map<String,String>();
List<String> lst = new List<String>();
for(String t: customvalues.keySet()){
    String test= customvalues.get(t);
for(String s: Selected.keySet()){
    String Sample= Selected.get(s);
//how to restrict duplicates here intering into this loop
if(test.equals(s)){ lst.add(Sample);
    }
  }
}
if(lst!=null){
for(Integer i=0;i<=lst.size();i++){
Lead le = new Lead();
le.LastName=lst[0];
le.Company = lst[1];
le.Status = lst[2];
le.LightiningEd__City__c = lst[3];
le.LightiningEd__State__c = lst[4];
le.LightiningEd__Country__c = lst[5];
LeadList.add(le);
} if(!LeadList.isEmpty()){
upsert LeadList;
}

Thanks I adavance,If anybody having idea please let me know.
{!pramod_nishane}{!pramod_nishane}
Hi basha sk,

Considering values of Map - 
customvalues = {1-> 'A',2->'B',3->'C'}
Selected = {1-> 'A',2->'E',3->'M'}


Your code - 

    for(String t: customvalues.keySet()){
        String test= customvalues.get(t); A
        for(String s: Selected.keySet()){
            String Sample= Selected.get(s); A
            //how to restrict duplicates here intering into this loop
            if(test.equals(s)){
                lst.add(Sample);
            }
        }
    }

Optimised code  :- 

for(String t: customvalues.keySet()){
        for(String s: Selected.keySet()){
            if(customvalues.get(t) != Selected.get(s)){ // you can check direct values instead of stoaring in variables
                if(lst.contains(Selected.get(s))){  // check for contains in list
                    lst.add(Sample);
                }
            }
        }
    }


Also contains method of List is now available in Apex, starting in Spring '18'
(https://developer.salesforce.com/docs/atlas.en-us.212.0.apexcode.meta/apexcode/apex_methods_system_list.htm#apex_System_List_contains).

Let me know in case of any concerns.

Please mark this answer as the solution/ best answer if it solves your purpose so that it can help other community members.

Thanks,
Pramod Nishane
Salesforce Consultant
Varasi LLC
www.varasi.com