Salesforce Fact #753 | Save one for loop using clone() method

Suppose we need to find out which accounts have related contacts or no related contacts in the apex code. 

Now as per the usual logic, we would fetch the data from contact object based on the AccountIds which would give us the count of accounts having related contacts. And after that, we would run another loop to iterate over the master account list and check which one does not have any related contact.

Well, we can use the clone() method of Set class which would help us to save one loop.

Attached is the screenshot.

Note: The SOQL and list lengths are only for demonstration purpose. As per the best practice, SOQLs need to be as much as selective with proper access checks to retrieve only the intended records.



Comments

Popular posts from this blog

Salesforce Fact #192 | Call batch apex from flow

Salesforce Fact #457 | Get current user role name in flow