0

I'm new to Map concept and ending up writing queries in for loop causing APEX violations.

I have a list of Ids on which I loop over and call a method. To this method I'm passing the Id and another list of Ids. I need a list of records which loop over the first list and return the values which are not in list 2. Below logic is working totally fine but it is violation a lot of apex practices. Can someone help me to refine this code please that would be of great help for me to understand code simplification.

My code:

 public static void method1(){
     List<String> idsList1 = ['id1','id2','id3'];

     List<String> idsList2 = ['id4','id5','id6'];

     for(String list2 : idsList2){
      List<Obj1> obj = method2(list2, idsList1);
      //do some logic
     }
    }

    //In this method we query records with recId and then exclude the records which match with alllist1
        public static List<Obj2> method2(String recId, List<String> alllist1){
             List<obj2> objList= [Select Id, f1_c, f2__c where f1__c =: recId]; //I will have multiple recs on this with same recId on obj2
             List<Obj2> finalList = new List<Obj2>();
             for(obj2 list2Rec: objList){
                for(String list1Rec: alllist1){
                   if(list1Rec != list2Rec.Id){
                      finalList.add(list2Rec);  
                   }
                 }
             }
             return finalList;
        }
3
  • It would help to explain the business logic you are attempting to perform. This overly generic code with no backing explanation is difficult to provide an accurate answer for.
    – sfdcfox
    Oct 31, 2023 at 22:36
  • Set class methods retainXXX and removeXXX will be useful to you
    – cropredy
    Oct 31, 2023 at 22:48
  • I think you want records with Ids in one list but not the other. You can do that with pure soql. Do ... WHERE Id IN :idsList1 AND Id NOT IN :idsList2
    – MadMax
    Oct 31, 2023 at 23:15

0

Browse other questions tagged .