Iterable Variable in For Loops
What Is the Iterable Interface?
In Apex, Iterable enables you to:
Create custom classes that return a collection.
Iterate on that class with a for loop, just like you would on a list or set.
This is useful when:
You require custom iteration logic (e.g., filtering, batching).
You prefer clean and consistent looping syntax.
Steps to Implement and Use Iterable
in Apex
1. Create a Class That Implements Iterable<T>
public class MyIterable implements Iterable {
private List strings;
// Constructor that initializes the strings field with the provided list
public MyIterable(List<String> strings) {
this.strings = strings;
}
// Iterator method that returns an iterator for the strings list
public Iterator<String> iterator() {
return strings.iterator();
}
}
2. Create a Test Class
@IsTest
public class MyIterableTest {
@IsTest
static void testIterableForLoop() {
// Step 1: Create a list of strings
List<String> strings = new List<String>{'Hello', 'World'};
// Step 2: Create an instance of MyIterable with the list of strings
MyIterable myIterableInstance = new MyIterable(strings);
// Step 3: Add a debug statement to verify test execution
System.debug('Running the for loop...');
// Step 4: Use a for loop to iterate over the MyIterable instance
for (String str : myIterableInstance) {
// Step 5: Print each string using System.debug
System.debug('String: ' + str);
}
}
}