Preventing Collection Modification During Iteration in Apex (Set) – Winter’25 Release

In Apex, modifying a Set while iterating over it was previously allowed, but it often led to unpredictable behavior. Developers encountered issues such as skipped elements, multiple processes on the same element, or unexpected errors. To address this, from API version 61.0, Apex introduced a restriction that prevents modifying a Set during iteration. Join us to learn about Preventing Collection Modification During Iteration in Apex (Set) winter’s 25 release changes.

If you attempt to modify a Set during iteration in API v61.0 or higher, Apex will throw a System.FinalException, ensuring consistency and preventing these common pitfalls.

The Problem Before API v61.0 or Winter25

Before API version 61.0, modifying a Set during iteration could result in:

  • Skipped elements in the iteration.
  • Processing the same element multiple times.
  • Inconsistent behaviour and hard-to-diagnose bugs.

To improve reliability, the restriction was introduced, preventing modifications during iteration and throwing an exception if attempted.

Let’s take a look at an example of how this restriction works in API version 61.0 and later:

Set<String> names = new Set<String>{'Alice', 'Bob', 'Charlie'};
for (String name : names) {
    if (name.startsWith('A')) {
        names.remove(name);  // This throws a System.FinalException in API v61.0+
    }
}

If you try to remove ‘Alice’ from the set while iterating over it, the code will throw this exception:

System.FinalException: Cannot modify a collection while it is being iterated.

Learn about Salesforce Apex Best Practices.

How to Safely Modify Sets During Iteration:

Instead of modifying the original set during iteration, you can store the elements you want to modify or remove in a separate collection and make the changes after the iteration.

Set<String> names = new Set<String>{'Alice', 'Bob', 'Charlie'};
Set<String> toRemove = new Set<String>();

// Identify elements to remove
for (String name : names) {
    if (name.startsWith('A')) {
        toRemove.add(name);  // Add to a temporary collection
    }
}

// Remove elements after iteration
names.removeAll(toRemove);

Conclusion:

Modifying a Set during iteration is no longer allowed starting with API version 61.0, and attempting to do so will result in a System.FinalException. By adopting safe practices like using temporary collections or iterators, you can ensure your code runs reliably and avoids the pitfalls of modifying collections during iteration.

Satyam parasa
Satyam parasa

Satyam Parasa is a Salesforce and Mobile application developer. Passionate about learning new technologies, he is the founder of Flutterant.com, where he shares his knowledge and insights.

Articles: 9

Leave a Reply

Your email address will not be published. Required fields are marked *