+ Start a Discussion
golugolu 

split a list into two lists and insert

Hi,
I want to split the list into two lists and insert a custom object record if the original list size is greater than 5000. Can someone please provide the code snippet for it? In the below code if the size of activityids is greater than 5000, then one more history rec should be inserted storing the activity ids greater than 5000. 
 
//if(activityIds.size() > 5000) split the list into  different list to insesrt
        History__c historyrec = new History__c();
        historyrec.Message__c = message;
        historyrec.Schedule_Date_Time__c = scheduleDateTime;
        historyrec.Activity_Ids__c = String.valueOf(activityIds);
        historyrec.Status__c = status;
        insert historyrec;

 
Deepali KulshresthaDeepali Kulshrestha
Hi golu,
Greetings to you!

- Here I am sharing my code which is successfully working in my Org. You can use is to split your list. Remember to replace the sObject name.
- Use upsert instead of insert.

    // Here my account list has 83 records i am spliting my records in 40 in one list and remaining in another list
    List<Account> acList=[SELECT Id,Name FROM Account limit 10000];
    System.debug('Size-->'+acList.size());
    //Created two lists to split the main list.
    List<Account> acList1=new List<Account>();
    List<Account> acList2=new List<Account>();
    //For-each loop on main list.
    for (Account ac: acList){
        if(acList1.size()<40){
            Account ac1=new Account();
            ac1=ac;
            acList1.add(ac1);
        }else{
            Account ac2=new Account();
            ac2=ac;
            acList2.add(ac2);
        }
    }   
    System.debug(acList1.size());
    
    System.debug(acList2.size());
    
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.