The idiomatic way to do this in other languages without iterator semantics is to iterate through the list backwards.

For example:

public static List<Object> removeAll(List<Object> target, Object toRemove) {
    for(Integer i = target.size() - 1; i >= 0; i--) {
        if(target[i].equals(toRemove)) {
            target.remove(i);
        }
    }

    return target;
}
Answer from Alex Tennant on Stack Exchange
🌐
Reddit
reddit.com › r/salesforce › iterate through list and remove items
r/salesforce on Reddit: Iterate through list and remove items
May 6, 2012 -

Does anyone have a code example of how to iterate through a list and remove any list items that match the items in another list? So, say I have a list of CDs and a list of LPs, I want to look through the list of CDs and remove any that are for the same artist and album as an item in the list of LPs. I'm thinking I'm probably going to need a map but I've never written a map before and can't seem to find any examples of them that remove things.

UPDATE: Thanks for all the input guys. I'm totally going to save this thread and use all this stuff in the future. As for the current scenario. I found a different solution. I was attempting to avoid an error message but the client actually wants to see the error message SO totally different scenario :)

Top answer
1 of 3
2

I'd convert your list to sets, and use set.contains, and set.removeAll. Check out the set docs.

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_set.htm#apex_System_Set_methods

I'd do it like this (provided I am understanding your question). it could be a set of anything, I'm just using Ids since I don't know what your data type is. You could the convert the set back into a list if you need. Or you can use the suggestion below of iterating the list, recording the index position (which might be a pain/inefficient to get since lists don't have a contains method, so you'd need to iterate and search the list for every element).

//set created from your first list, Im calling it listA (provided your list is a list of ids)
set<id> firstSet = new set<id>(listA);

//set created from your second list, which I'm calling listB (provided your list is a list of ids)
set<id> secondSet = new set<id>(listB);

//temp variable to hold the things to delete
list<id> thingsToRemove = new list<id>();

//iterate the first set
for(id thisId : firstSet)
{
    //see if this thing is in the second set
    if(secondSet.contains(thisId))
    {
	    //if so, then add it to our list of things to remove
	    thingsToRemove.add(thisId);
    }
}

//remove the things from the set
firstSet.removeAll(thingsToRemove);
2 of 3
1

Edit: Just realized that if you are actually storing albums as sObjects and can retrieve with SOQL, none of this is necessary. It would be one line:

List<Album> filteredCDs = [ Select Id, Name... etc from Album Where Id in : CDs and Id Not in : LPs ];

Given that, I bet all my assumptions were wrong, eh? Perhaps I should have asked more questions, but hey, nothing like writing a novel about code... while at work... supposedly working on work related code...


The problem with lists is you can only remove items by passing an index. Once it's removed, the indeces are reset, so it's pretty much impossible to iterate through a list and remove items while you're in the same loop.

Here's how I'd do it without maps (and by making big assumptions about your existing code):

private List<Album> filterCDs(List<Album> CDs, List<Album> LPs) {

    List<Album> filteredCDs = new List<Album>();

    for ( Album CD: CDs) {
        for ( Album LP : LPs ) {
            if ( LP.ArtistName != CD.ArtistName && LP.AlbumName != CD.AlbumName )
                filteredCDs .add(CD);
        }
    }

    return filteredCDs;
}

So this doesn't actually remove anything, it just only returns the cds that don't appear in the LP list. If your lists are large, this is crazy inefficient though, with the number of comparisons being CDs.size() * LPs.size().

Maps are not as scary as they seem, and are extremely useful! They're basically the same as a list/array, but can use an index other than an integer. What's cool about maps is you can build one with SOQL, and it gives you a kind of list where each index is the ID of the record.

Here's how I'd do it with a map (assuming albums are an sObject and not just a Class):

private List<Album> filterCDs(List<Album> CDs, List<Album> LPs) {

    Map<Id, Album> LPMap = new Map<Id, Album>([ Select Id from Album where Id in : LPs ]);

   /*
    ^ returns a kind of list where the indexes are the Ids of each record, like:

        LPMap = {
            'albumid0' = Album{
                Id = 'albumid0'
            },
            'alumbid1' = Album{
                Id = 'albumid1'
            },...
        }
    */

    List<Album> filteredCDs = new List<Album>();

    for ( Album CD: CDs) { // iterate through CDs
        if ( !LPMap.containsKey(CD.Id) ) // if the LP map does *not* contain this CD id
            filteredCDs.add(CD); // add it to the new list
    }

    return filteredCDs;
}

Calling LPMap.containsKey(some_album_id) is better than iterating through the entire list and physically checking if an album with the same title/artist is present. It's similar to checking whether or not LPMap.get(some_album_id) == null. And now the number of comparisons is just the size of the CDs list.

Definitely find more info about maps and how to build them manually with .put(key, value). Removing is just .remove(key).

Anyway, hope that makes some amount of sense... I'd have to know more about how you're already organizing things to know whether or not everything I've just typed is utterly useless or not!

Discussions

salesforce - delete multiple objects which are inside array in Apex - Stack Overflow
Very new to Apex and never touched java, basically what I am trying to do is delete all records then insert records inside multiple custom objects. Bellow is my code for just the deleting part but ... More on stackoverflow.com
🌐 stackoverflow.com
salesforce - Iterating Through A List And Removing Duplicate Items in apex - Stack Overflow
I want to remove the duplicate entries based on the Name field from the list. Below is my Code.. public class EPM_Contact_Component_Class { public List conList { get; set; } public List result { get; set; } public JCT_Hospital_Model__c jctObj { get; set; } public Set myset { get; set; } public EPM_Contact_Component_Class(ApexPages... More on stackoverflow.com
🌐 stackoverflow.com
collections - Remove all duplicate and the original elements from a list - Stack Overflow
I have a list of sObject elements. I want to remove the duplicate element having the same record name along with the original record . Like suppose if I have a list of element having record names ... More on stackoverflow.com
🌐 stackoverflow.com
salesforce - How to remove a class instance from a List of class - Stack Overflow
Remove should get an integer index. Dont forget to adjust your index after removing an object to not skip object from list. More on stackoverflow.com
🌐 stackoverflow.com
November 12, 2013
🌐
Salesforce
trailhead.salesforce.com › trailblazer-community › feed › 0D54S00000Cf8nGSAR
How to delete a item from a list - Trailhead - Salesforce
August 30, 2021 - Skip to main content · Register now for TDX! Join the must-attend event to experience what’s next and learn how to build it
🌐
Stack Overflow
stackoverflow.com › questions › 28631505 › delete-multiple-objects-which-are-inside-array-in-apex
salesforce - delete multiple objects which are inside array in Apex - Stack Overflow
List<String> objectNames = new List<String> {'More_Info_Request__c', 'Object1__c', 'Object2__c'}; for (String objectName : objectNames) { List<SObject> existing = Database.query('select id from ' + objectName); delete existing; } ... Sign up to request clarification or add additional context in comments. ... Using query in a loop is a bad decision! This link will be very helpful as long as you have just started with apex:developer.salesforce.com/page/Apex_Code_Best_Practices Are you using class or it is inside of a some trigger?
🌐
Sfdcmeet
sfdcmeet.com › development › apex-in-salesforce › list-in-apex-collections
List in Apex Collections – Salesforce CRM Online Training and Knowledge Sharing
Sort() – Sorts the items in a list listNames.sort(); System.debug(listNames); ... remove() – remove list element in a specified index To remove the 2nd element in the above list – listNames
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 38999502 › iterating-through-a-list-and-removing-duplicate-items-in-apex
salesforce - Iterating Through A List And Removing Duplicate Items in apex - Stack Overflow
I want to remove the duplicate entries based on the Name field from the list. Below is my Code.. public class EPM_Contact_Component_Class { public List<Hospital_Contacts__c> conList { get; set; } public List<Hospital_Contacts__c> result { get; set; } public JCT_Hospital_Model__c jctObj { get; set; } public Set<Hospital_Contacts__c> myset { get; set; } public EPM_Contact_Component_Class(ApexPages.StandardController controller) { } public List<Hospital_Contacts__c> getContacts() { conList = new List<Hospital_Contacts__c>(); jctObj = new JCT_Hospital_Model__c(); jctObj = [Select EPM_Model__r.Name
🌐
SFDC Stop
sfdcstop.com › 2021 › 09 › list-data-structure-in-apex-apex-data.html
List Data Structure in Apex | Apex Data Structure Tutorials by SFDC Stop - SFDC Stop
September 10, 2021 - As you can see above, we had 5 ... list. The element 3 was present at index 2 so, we removed 3 from the list by using remove() method and the updated list is: 1, 2, 4, 5....
🌐
Camp Apex
campapex.org › lesson › 640cfcaf6e4efea481c54dd2
List - Clear and Remove | Camp Apex
There are a few ways to do this, depending on what you know about your list. If you already know elaine@campapex.org is in the first index, you can simply use the remove(index) instance method to remove an element based on it's index:
🌐
Forcetalks
forcetalks.com › home › salesforce® discussions › how to remove elements from a list in apex on button click in salesforce?
How to remove elements from a list in apex on button click in Salesforce? - Forcetalks
December 6, 2019 - Tagged: Button Clicks, Salesforce Apex, Salesforce Button, Salesforce Elements ... https://salesforce.stackexchange.com/questions/55310/how-to-remove-items-from-a-dynamic-list-in-lightning-component
🌐
CRS Info Solutions
crsinfosolutions.com › home › list class in salesforce apex
List Class in Salesforce Apex
Salesforce Training
It is part of the Salesforce Apex Collection framework and provides methods to manipulate lists of objects. Lists can store objects of any data type, including custom and sObject types. Key methods include adding elements (add()), retrieving elements (get()), removing elements (remove()), checking ... I have enrolled for Salesforce Admin and development online course at CRS info solutions. It’s really the best training i have ever taken and syllabus is highly professional
Rating: 5 ​
🌐
S2 Labs
s2-labs.com › home › delete | apex dml standalone statement
Delete In Apex | Salesforce Developer Tutorials
List < Contact > conList = [SELECT Name FROM Contact]; Map < String, ID > mMap = new Map < String, ID > (); for (Contact c: conList) { mMap.put(c.Name, c.Id); } List < Contact > uniqList = new List < Contact > (); List < Contact > delList = new List < Contact > (); Set < String > sSet = mMap.keySet(); Set < ID > uniqSet = new Set < ID > (); for (String s: sSet) { uniqSet.add(mMap.get(s)); } for (Contact c1: conList) { if (uniqSet.contains(c1.Id)) uniqList.add(c1); else delList.add(c1); } delete delList; Use is Deleted=true & ALL ROWS keyword to get the deleted records from the recycle bin using SOQL. ALL ROWS keyword cannot be used in the query editor but can be used in the apex class or function while querying record in [].
Published   June 24, 2024
🌐
Stack Overflow
stackoverflow.com › questions › 48610285 › remove-all-duplicate-and-the-original-elements-from-a-list
collections - Remove all duplicate and the original elements from a list - Stack Overflow
List <Chair__c> chairList = [SELECT ID, Name FROM Chair__c ORDER BY Name ASC]; System.debug('chairListOrderbyName::'+chairList); List <String> chairNameList = new List <String>(); for(Integer i = 0; i < chairList.size();i++) { for(Integer j = 0;j < chairList.size();j++) { if(chairList[i].Name.equalsIgnoreCase(chairList[j].Name) && i != j) { chairList.remove(i); chairList.remove(j); } } } System.debug('chairList::'+chairList); list · collections · salesforce · apex ·
🌐
JanbaskTraining
janbasktraining.com › home › how to create list in salesforce and set methods: to ensure a bright career
How to Create List in Salesforce and Set Methods: To Ensure A Bright Career
April 2, 2024 - Apex List Methods: remove(index): It is responsible for the removal of the List element stored at the specified index, returning the element that was removed.
🌐
Forcetree
forcetree.com › 2013 › 05 › collections-in-apex-list-maps-and-sets.html
ForceTree.com: Collections in Apex: List, Maps and Sets
List<Account> listsample = [Select Id,Name from Account limit 5]; system.debug('The Account Name at index 0 is'+listsample[0].Name); system.debug('The size of the list is'+listsample.size()); //Adding a element to the list listsample.add(new Account(Name='testlistsample')); system.debug('The size of the list now is'+listsample.size()); //Remove a element from the list listsample.remove(5); system.debug('The size of the list now is'+listsample.size()); SET: A set is an unordered collection.