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
turbo2ohturbo2oh 

proper syntax for removing object from list

I have a list of objects and I need to be able to remove a specific object from the list. I've been trying to remove it by the ID or the object itself but neither seem to be working. 

 

I've seen it suggested on here that the best practice is to just move everything to a new list and exclude the unwanted object, but this list can be changed as many times as the user changes their mind which could get ugly fast. Is there no better solution?

 

Thanks!

Phil

Best Answer chosen by Admin (Salesforce Developers) 
kreshokresho
public static void removeObjectFromList(List<SObject> lst, SObject o) {
	for (Integer i = lst.size() - 1; i >= 0 ; --i) {
		if (lst.get(i) == o || lst.get(i).get('id') == o.get('id')) {
			lst.remove(i); 
		}
	}
}

 

All Answers

Andy BoettcherAndy Boettcher

Are you talking about a visual list or a List<sObject> within an APEX class?

 

I can think of relatively easy solutions to either, but wanted to check first.

 

-Andy

turbo2ohturbo2oh

List<sobject>

Andy BoettcherAndy Boettcher

There really isn't anything too nasty about pulling the list into a Method, creating a new list, and looping through the user's selection to stick them in a new list.

 

Then - you'll just assign the new list back to the old list - and it will return to the screen.  Rinse and repeat, shouldn't really be much of a mess?

 

-Andy

Hpandey_ForceLabsHpandey_ForceLabs

That's shouldn't  be not so nasty - repopulating list or refreshing list with updated content thereby removing unwanted objects 

LakshmanLakshman

I would suggest you to use Set instead of List. Set has built in method called remove which has argument "Set Element e" (in your case Sobject) and return type Boolean which is true if the element is removed and false the other way.

 

Another way would be like using Map<Id,List<Sobject>>(). Both would meet your requirement and would be definitely faster than iterating the List and removing.

 

Regards,

Lakshman

kreshokresho
public static void removeObjectFromList(List<SObject> lst, SObject o) {
	for (Integer i = lst.size() - 1; i >= 0 ; --i) {
		if (lst.get(i) == o || lst.get(i).get('id') == o.get('id')) {
			lst.remove(i); 
		}
	}
}

 

This was selected as the best answer
turbo2ohturbo2oh

Thanks for the help guys! I ended up using a solution similiar to Lakshman's suggestion of a list inside a map but I'll store this code snippet for future use and marked it as the solution since it really answers the orgiinal question.