top of page

Mastering Iteration in Apex: Using Iterable for Simplified Loops

Writer's picture: Neeraj SinghNeeraj Singh

Salesforce Apex Iterable

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

Rated 0 out of 5 stars.
No ratings yet

Add a rating

Contact Us

Thanks for submitting!

Head Office - Flat No 3B, Aruna Abasan 2, Arunachal,Hatiara,Kolkata,West Bengal,India

Branch - 5/3 Ebony Block, Astha Twin City, Telco,

Jamshedpur , Jharkhand

Mob - + 919830839090

queries@forceapozee.com
neeraj@forceapozee.com

© 2026 by Force Apozee.

bottom of page