Introduction
Efficient iteration is key to writing clean and maintainable Apex code. With the introduction of the Iterable interface, Salesforce developers can now iterate through lists and sets more seamlessly in for loops. This enhancement streamlines code readability and efficiency, especially when working with collections.
Where Does This Apply?
This feature is available in:
Lightning Experience and Salesforce Classic
Enterprise, Performance, Unlimited, and Developer editions
How Iterable Works in Apex Iterable for Loop
Previously, iterating over lists and sets required direct initialization of collections within for loops. Now, with Iterable, we can iterate over collections more intuitively Apex Iterable for Loop.
Simple List Iteration with Iterable
Consider the following example, where we iterate through a list of strings:
Iterable<String> stringIterator = new List<String>{'Hello', 'World!'};
for (String str : stringIterator) {
System.debug(str);
}
This allows direct iteration using the Iterable type, improving readability and flexibility.
Implementing Iterable in a Custom Class
To take it a step further, we can implement the Iterable interface in a class to return a set of strings:
public class MyIterable implements Iterable<String> {
public Iterator<String> iterator() {
return new Set<String>{'Hello', 'World!'}.iterator();
}
}
for (String str : new MyIterable()) {
System.debug(str);
}
Here, the MyIterable class implements Iterable<String>, and the iterator() method returns a set iterator. This makes it easy to reuse and customize iterable objects across different scenarios.
Benefits of Using Iterable
Improved Code Readability: Using Iterable makes loops more intuitive and clean.
Reusability: Custom implementations of Iterable allow flexible iteration logic.
Consistency: Ensures a standard approach to iterating over collections in Apex.
Conclusion
The Iterable interface in Apex simplifies working with lists and sets, making your code more efficient and readable. Whether you're iterating over simple collections or implementing a custom iterable class, this feature enhances code reusability and maintainability in Salesforce development.
Comments