{"id":2380,"date":"2026-10-18T09:00:00","date_gmt":"2026-10-18T03:30:00","guid":{"rendered":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/"},"modified":"2026-11-15T11:30:14","modified_gmt":"2026-11-15T06:00:14","slug":"apex-custom-iterator-iterable","status":"publish","type":"post","link":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/","title":{"rendered":"Custom Iterators and Iterable in Apex Explained"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">An Apex Custom Iterator lets you decide how a for loop moves through data. Instead of looping a list that already exists, you supply items one at a time. So you can page through a long result, skip rows by a rule, or feed Batch Apex from something other than a query.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This post builds on <a href=\"https:\/\/swapnilzambare.com\/blog\/apex-collections-list-set-map\/\">Apex collections<\/a> and <a href=\"https:\/\/swapnilzambare.com\/blog\/batch-apex-start-execute-finish\/\">Batch Apex<\/a>. We will page through course records for Bright Path Tutors.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is an Apex Custom Iterator?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">An Apex Custom Iterator is a class that implements <code>Iterator&lt;T&gt;<\/code> with two methods. <code>hasNext()<\/code> answers whether another item exists, and <code>next()<\/code> returns the current item and moves forward.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a ticket counter. The clerk checks whether anyone is still in the queue, then calls the next person. Your iterator is the clerk, and the queue is your data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why an Apex Custom Iterator Matters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Most of the time a plain List is fine. You need an iterator when the data does not already sit in memory, or when the rule for what comes next is not a simple position.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Common cases are paging through an external API, walking a parent-child tree, or giving Batch Apex a scope that SOQL cannot express. An Apex Custom Iterator also keeps that logic in one class, instead of spreading index maths through your code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How an Apex Custom Iterator Works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">With an Apex Custom Iterator, a for loop does not read your data directly. It asks for an iterator, then calls two methods in a cycle until the first one returns false.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-1-1024x640.png\" alt=\"Apex Custom Iterator diagram showing how a for loop calls hasNext and next\" class=\"wp-image-2378\" srcset=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-1-1024x640.png 1024w, https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-1-300x188.png 300w, https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-1-768x480.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">How a for loop drives hasNext and next.<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">The Iterator Class<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class CourseIterator implements Iterator&lt;Course__c&gt; {\n    private List&lt;Course__c&gt; items;\n    private Integer index = 0;\n\n    public CourseIterator(List&lt;Course__c&gt; items) {\n        this.items = items;\n    }\n    public Boolean hasNext() {\n        return index &lt; items.size();\n    }\n    public Course__c next() {\n        return items[index++];\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>index++<\/code> returns the current value and then adds one, so each call moves forward.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Making a Class Loopable<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A for loop cannot take an iterator directly. It needs an <code>Iterable<\/code>, which is a class that knows how to hand one out.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class CourseBag implements Iterable&lt;Course__c&gt; {\n    private List&lt;Course__c&gt; items;\n    public CourseBag(List&lt;Course__c&gt; items) { this.items = items; }\n    public Iterator&lt;Course__c&gt; iterator() {\n        return new CourseIterator(items);\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now the loop reads naturally.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CourseBag bag = new CourseBag([SELECT Id, Name FROM Course__c LIMIT 5]);\nfor (Course__c c : bag) {\n    System.debug(c.Name);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The log prints each course name in turn.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Python Basics\nSQL Basics\nStatistics<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Skipping Items with a Rule<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The real value shows when <code>next<\/code> does more than return the next slot.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class PaidOnlyIterator implements Iterator&lt;Enrolment__c&gt; {\n    private List&lt;Enrolment__c&gt; items;\n    private Integer i = 0;\n    public PaidOnlyIterator(List&lt;Enrolment__c&gt; items) { this.items = items; }\n\n    public Boolean hasNext() {\n        \/\/ Look ahead past unpaid rows\n        while (i &lt; items.size() &amp;&amp; items[i].Fee_Status__c != 'Paid') { i++; }\n        return i &lt; items.size();\n    }\n    public Enrolment__c next() { return items[i++]; }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The loop that uses this never sees an unpaid record, and the calling code stays clean.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Iterator and Iterable Methods<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This table lists what each interface asks you to write.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Interface<\/th><th>Method<\/th><th>Returns<\/th><\/tr><\/thead><tbody><tr><td>Iterator<\/td><td>hasNext()<\/td><td>Boolean, is there another item<\/td><\/tr><tr><td>Iterator<\/td><td>next()<\/td><td>The next item, then moves on<\/td><\/tr><tr><td>Iterable<\/td><td>iterator()<\/td><td>A fresh Iterator for this data<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Using Iterable with Batch Apex<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Batch Apex normally takes a QueryLocator. When your scope cannot be written as SOQL, return an <code>Iterable<\/code> instead.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class FeeBatch implements Database.Batchable&lt;Course__c&gt; {\n    public Iterable&lt;Course__c&gt; start(Database.BatchableContext bc) {\n        return new CourseBag([SELECT Id, Name, Fee__c FROM Course__c LIMIT 1000]);\n    }\n    public void execute(Database.BatchableContext bc, List&lt;Course__c&gt; scope) {\n        for (Course__c c : scope) { c.Fee__c = c.Fee__c * 1.05; }\n        update scope;\n    }\n    public void finish(Database.BatchableContext bc) {\n        System.debug('Fee batch finished');\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">There is a trade-off. A QueryLocator can return up to 50 million records, while an Iterable is built in memory and is limited to the normal 50,000 query rows.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Iterator vs Iterable<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These two names confuse most developers. This table separates them.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Iterator<\/th><th>Iterable<\/th><\/tr><\/thead><tbody><tr><td>Purpose<\/td><td>Walks the data<\/td><td>Supplies a walker<\/td><\/tr><tr><td>Methods<\/td><td>hasNext, next<\/td><td>iterator<\/td><\/tr><tr><td>Keeps position<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Works in a for loop<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Batch start method<\/td><td>Not alone<\/td><td>Yes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-2.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-2-1024x640.png\" alt=\"Apex Custom Iterator compared with the Iterable interface\" class=\"wp-image-2379\" srcset=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-2-1024x640.png 1024w, https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-2-300x188.png 300w, https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-diagram-2-768x480.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">Iterator compared with Iterable in Apex.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In short, the Iterable is the book and the Iterator is your finger on the page. You need both for a custom loop.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A Real Apex Custom Iterator Example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Bright Path pulls courses from a partner API that returns 50 records per page. The code should loop through all of them as if they were one list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: The Paging Iterator<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class ApiPageIterator implements Iterator&lt;String&gt; {\n    private List&lt;String&gt; page = new List&lt;String&gt;();\n    private Integer pos = 0;\n    private Integer pageNo = 1;\n    private Boolean more = true;\n\n    public Boolean hasNext() {\n        if (pos &lt; page.size()) { return true; }\n        if (!more) { return false; }\n        loadPage();\n        return pos &lt; page.size();\n    }\n    public String next() { return page[pos++]; }\n\n    private void loadPage() {\n        \/\/ In real code this would be an HTTP callout\n        page = MockApi.fetch(pageNo);\n        pos = 0;\n        pageNo++;\n        if (page.isEmpty()) { more = false; }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The caller never knows that pages exist. The iterator fetches the next page only when the current one runs out.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Wrap It<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class ApiCourses implements Iterable&lt;String&gt; {\n    public Iterator&lt;String&gt; iterator() { return new ApiPageIterator(); }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Loop It<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Integer count = 0;\nfor (String name : new ApiCourses()) {\n    count++;\n}\nSystem.debug('Total courses from API: ' + count);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The output shows one number, even though several pages were fetched.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Total courses from API: 128<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These are the pieces and their jobs.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Class<\/th><th>Interface<\/th><th>Job<\/th><\/tr><\/thead><tbody><tr><td>ApiPageIterator<\/td><td>Iterator<\/td><td>Fetches pages and hands out items<\/td><\/tr><tr><td>ApiCourses<\/td><td>Iterable<\/td><td>Gives the loop a fresh iterator<\/td><\/tr><tr><td>MockApi<\/td><td>Helper<\/td><td>Stands in for the real callout<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes with an Apex Custom Iterator<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Implementing Iterator but trying to use it directly in a for loop.<\/li>\n\n<li>Moving the index inside hasNext, which can skip items.<\/li>\n\n<li>Forgetting to reset position, so a second loop finds nothing.<\/li>\n\n<li>Putting SOQL inside next, which runs a query per record.<\/li>\n\n<li>Using an Iterable in Batch Apex for millions of rows, which breaks the row limit.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for an Apex Custom Iterator<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Keep hasNext free of side effects where you can.<\/li>\n\n<li>Return a new iterator each time iterator() is called.<\/li>\n\n<li>Prefer a plain List when the data already fits in memory.<\/li>\n\n<li>Use QueryLocator in Batch Apex unless your scope cannot be queried.<\/li>\n\n<li>Write a test that loops the iterator twice to prove it resets.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Write an iterator that returns only even numbers from a List of Integers. Then wrap it in an Iterable and loop it. Hint: do the skipping inside hasNext.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Most Asked Apex Custom Iterator Interview Questions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Apex Custom Iterator questions appear in advanced developer interviews.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Apex Custom Iterator Interview Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1: What is an iterator in Apex?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An Apex Custom Iterator is a class implementing Iterator with hasNext and next, which controls how a loop walks data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2: What two methods does Iterator need?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An Apex Custom Iterator needs hasNext, which returns a Boolean, and next, which returns the next item.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3: What does the Iterable interface require?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It needs one method called iterator, which returns a fresh Iterator.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4: Can you use an Iterator directly in a for loop?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. The loop needs an Iterable, so you wrap the iterator in one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5: Why would you write a custom iterator?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You write one to page through data, skip items by a rule, or walk a source that is not a simple list.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6: Does a List already support looping?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Lists, sets and maps all work in for loops without any extra code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7: Where is Iterable used besides loops?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the start method of Batch Apex, when the scope cannot be a SOQL query.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8: What does next return?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It returns the current item, and it also moves the position forward for the following call.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Intermediate Apex Custom Iterator Interview Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9: What is the row limit when Batch Apex uses an Iterable?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The normal query limit of 50,000 rows, because the collection is built in memory.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10: What is the limit with a QueryLocator instead?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Up to 50 million records, since the platform streams them in chunks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11: Why should hasNext avoid changing state?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because a loop may call it more than once. Changing position there can skip records.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12: How do you make an iterator reusable?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Return a new iterator object from iterator() each time, rather than sharing one instance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q13: Can an iterator return sObjects?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Iterator is generic, so it can return any type, including sObjects and wrappers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q14: What happens if next is called when hasNext is false?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You get a list index out of bounds error. So the loop must always check first.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q15: Can one class implement both Iterator and Iterable?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, and it is common for small cases. The iterator method then returns this.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q16: Is a custom iterator faster than a list loop?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Usually not. Its value is control over the source, not raw speed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Advanced Apex Custom Iterator Interview Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q17: Scenario: you must process records from a REST API in Batch Apex. How?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Write an Iterable whose iterator makes callouts page by page, then return it from start and mark the batch Database.AllowsCallouts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q18: How would you iterate a parent-child tree?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep a stack inside the iterator. Pop a node in next, then push its children so they come later.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q19: What are the heap risks with iterators?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Loading every page into one list uses heap. So drop processed pages and keep only the current one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q20: How do you test an iterator properly?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test an empty source, a single item, several items and a second full loop to prove it resets.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q21: Scenario: the loop silently skips every other record. What is wrong?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The position is probably being moved in both hasNext and next. So move it in next only.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q22: When is an iterator the wrong tool?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When a simple query with ORDER BY and LIMIT gives the same result. Then plain SOQL is clearer and cheaper.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q23: Can you combine an iterator with the Stub API?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. You can stub the Iterable so tests supply fixed items without any callout.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q24: How does Iterable help a managed package?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Subscribers can pass their own Iterable, so your batch runs on data you never anticipated.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q25: Does an Apex Custom Iterator count against SOQL limits?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Only the queries inside it count. So one query in the constructor is fine, while a query inside next is not.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q26: Can an Apex Custom Iterator be used in a Flow?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Not directly. Instead, expose an invocable method that returns a List, because Flow works with collections.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q27: How does an iterator differ from a wrapper class?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A wrapper carries data for one row. However, an iterator decides the order and supply of many rows.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q28: Scenario: memory errors while looping a large API result. What do you change?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep only the current page in the iterator and clear the previous one. Then heap stays flat as the loop runs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q29: Should every list get a custom iterator?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. Use one only when the supply rule is unusual, because plain lists are simpler for readers to follow.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/developer.salesforce.com\/docs\/atlas.en-us.apexcode.meta\/apexcode\/apex_classes_iterable.htm\" target=\"_blank\" rel=\"noopener noreferrer\">Apex Developer Guide: Custom Iterators<\/a><\/li>\n\n<li><a href=\"https:\/\/developer.salesforce.com\/docs\/atlas.en-us.apexref.meta\/apexref\/apex_interface_System_Iterator.htm\" target=\"_blank\" rel=\"noopener noreferrer\">Apex Reference: Iterator Interface<\/a><\/li>\n\n<li><a href=\"https:\/\/developer.salesforce.com\/docs\/atlas.en-us.apexcode.meta\/apexcode\/apex_batch_interface.htm\" target=\"_blank\" rel=\"noopener noreferrer\">Apex Developer Guide: Using Batch Apex<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>An Apex Custom Iterator controls how a loop walks your data.<\/li>\n\n<li>Iterator needs hasNext and next, and Iterable needs iterator.<\/li>\n\n<li>A for loop takes an Iterable, not an Iterator.<\/li>\n\n<li>Batch Apex accepts an Iterable, but with the 50,000 row limit.<\/li>\n\n<li>Use a plain List when the data already fits in memory.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we send messages from code with <a href=\"https:\/\/swapnilzambare.com\/blog\/sending-email-from-apex\/\">Sending Email from Apex<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>An Apex Custom Iterator lets you decide how a for loop moves through data. Instead of looping a list that already exists, you supply&hellip;<\/p>\n","protected":false},"author":1,"featured_media":2377,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[239,8,96],"tags":[68,98],"swapz_series":[],"class_list":["post-2380","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-apex-fundamentals","category-salesforce","category-salesforce-developer","tag-advanced","tag-apex"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Apex Custom Iterator and Iterable Explained<\/title>\n<meta name=\"description\" content=\"Learn the Apex Custom Iterator and Iterable interfaces, how hasNext and next work, use with Batch Apex, plus the most asked interview questions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Apex Custom Iterator and Iterable Explained\" \/>\n<meta property=\"og:description\" content=\"Learn the Apex Custom Iterator and Iterable interfaces, how hasNext and next work, use with Batch Apex, plus the most asked interview questions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/\" \/>\n<meta property=\"og:site_name\" content=\"Swapnil Zambare - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-18T03:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-15T06:00:14+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Swapnil Zambare\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Swapnil Zambare\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/\"},\"author\":{\"name\":\"Swapnil Zambare\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#\\\/schema\\\/person\\\/10b09224c8bcc562716e86789427592a\"},\"headline\":\"Custom Iterators and Iterable in Apex Explained\",\"datePublished\":\"2026-10-18T03:30:00+00:00\",\"dateModified\":\"2026-11-15T06:00:14+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/\"},\"wordCount\":1631,\"publisher\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/apex-custom-iterator-iterable-featured.png\",\"keywords\":[\"Advanced\",\"Apex\"],\"articleSection\":[\"Apex Fundamentals\",\"Salesforce\",\"Salesforce Developer\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/\",\"name\":\"Apex Custom Iterator and Iterable Explained\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/apex-custom-iterator-iterable-featured.png\",\"datePublished\":\"2026-10-18T03:30:00+00:00\",\"dateModified\":\"2026-11-15T06:00:14+00:00\",\"description\":\"Learn the Apex Custom Iterator and Iterable interfaces, how hasNext and next work, use with Batch Apex, plus the most asked interview questions.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/#primaryimage\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/apex-custom-iterator-iterable-featured.png\",\"contentUrl\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/apex-custom-iterator-iterable-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Apex Custom Iterator featured image: code editor card with hasNext method\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-custom-iterator-iterable\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Custom Iterators and Iterable in Apex Explained\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/\",\"name\":\"Swapnil Zambare - Blog\",\"description\":\"Salesforce &amp; Tech Guides\",\"publisher\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#organization\",\"name\":\"Swapnil Zambare - Blog\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/site-icon-512.png\",\"contentUrl\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/site-icon-512.png\",\"width\":512,\"height\":512,\"caption\":\"Swapnil Zambare - Blog\"},\"image\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.linkedin.com\\\/in\\\/theSwapnilZambare\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#\\\/schema\\\/person\\\/10b09224c8bcc562716e86789427592a\",\"name\":\"Swapnil Zambare\",\"sameAs\":[\"https:\\\/\\\/swapnilzambare.com\\\/blog\"],\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/author\\\/swapnil-zambare\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Apex Custom Iterator and Iterable Explained","description":"Learn the Apex Custom Iterator and Iterable interfaces, how hasNext and next work, use with Batch Apex, plus the most asked interview questions.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/","og_locale":"en_US","og_type":"article","og_title":"Apex Custom Iterator and Iterable Explained","og_description":"Learn the Apex Custom Iterator and Iterable interfaces, how hasNext and next work, use with Batch Apex, plus the most asked interview questions.","og_url":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/","og_site_name":"Swapnil Zambare - Blog","article_published_time":"2026-10-18T03:30:00+00:00","article_modified_time":"2026-11-15T06:00:14+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-featured.png","type":"image\/png"}],"author":"Swapnil Zambare","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Swapnil Zambare","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/#article","isPartOf":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/"},"author":{"name":"Swapnil Zambare","@id":"https:\/\/swapnilzambare.com\/blog\/#\/schema\/person\/10b09224c8bcc562716e86789427592a"},"headline":"Custom Iterators and Iterable in Apex Explained","datePublished":"2026-10-18T03:30:00+00:00","dateModified":"2026-11-15T06:00:14+00:00","mainEntityOfPage":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/"},"wordCount":1631,"publisher":{"@id":"https:\/\/swapnilzambare.com\/blog\/#organization"},"image":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/#primaryimage"},"thumbnailUrl":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-featured.png","keywords":["Advanced","Apex"],"articleSection":["Apex Fundamentals","Salesforce","Salesforce Developer"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/","url":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/","name":"Apex Custom Iterator and Iterable Explained","isPartOf":{"@id":"https:\/\/swapnilzambare.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/#primaryimage"},"image":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/#primaryimage"},"thumbnailUrl":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-featured.png","datePublished":"2026-10-18T03:30:00+00:00","dateModified":"2026-11-15T06:00:14+00:00","description":"Learn the Apex Custom Iterator and Iterable interfaces, how hasNext and next work, use with Batch Apex, plus the most asked interview questions.","breadcrumb":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/#primaryimage","url":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-featured.png","contentUrl":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-custom-iterator-iterable-featured.png","width":2400,"height":1260,"caption":"Apex Custom Iterator featured image: code editor card with hasNext method"},{"@type":"BreadcrumbList","@id":"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/swapnilzambare.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Custom Iterators and Iterable in Apex Explained"}]},{"@type":"WebSite","@id":"https:\/\/swapnilzambare.com\/blog\/#website","url":"https:\/\/swapnilzambare.com\/blog\/","name":"Swapnil Zambare - Blog","description":"Salesforce &amp; Tech Guides","publisher":{"@id":"https:\/\/swapnilzambare.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/swapnilzambare.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/swapnilzambare.com\/blog\/#organization","name":"Swapnil Zambare - Blog","url":"https:\/\/swapnilzambare.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/swapnilzambare.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/09\/site-icon-512.png","contentUrl":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/09\/site-icon-512.png","width":512,"height":512,"caption":"Swapnil Zambare - Blog"},"image":{"@id":"https:\/\/swapnilzambare.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.linkedin.com\/in\/theSwapnilZambare"]},{"@type":"Person","@id":"https:\/\/swapnilzambare.com\/blog\/#\/schema\/person\/10b09224c8bcc562716e86789427592a","name":"Swapnil Zambare","sameAs":["https:\/\/swapnilzambare.com\/blog"],"url":"https:\/\/swapnilzambare.com\/blog\/author\/swapnil-zambare\/"}]}},"_links":{"self":[{"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/posts\/2380","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/comments?post=2380"}],"version-history":[{"count":1,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/posts\/2380\/revisions"}],"predecessor-version":[{"id":3205,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/posts\/2380\/revisions\/3205"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/media\/2377"}],"wp:attachment":[{"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/media?parent=2380"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/categories?post=2380"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/tags?post=2380"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=2380"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}