Set does have an iterator method; this is used internally by the for-in loop syntax. However, it does not implement the Iterable interface.

This notably means that new methods, like String.join, do not work with Sets, even though they have the iterator method.

As far as the documentation is concerned, I suspect that it's not documented because Set doesn't actually implement the Iterable interface. In other words, it's an internal method.

You'll also notice that other methods are not documented, either. For example, Object isn't documented, despite having two methods you can use (equals and hashCode).

I'm not sure you'd get a better answer short of having a real salesforce.com employee posting an answer.

Answer from sfdcfox on Stack Exchange
๐ŸŒ
Thesalesforcedev
thesalesforcedev.in โ€บ 2023 โ€บ 03 โ€บ 15 โ€บ using-custom-iterator-iterable-interface-in-apex
Using Custom Iterator & Iterable Interface in Apex โ€“ Welcome to The Salesforce Dev
May 17, 2025 - It accesses these elements sequentially. You donโ€™t need to know the underlying structure of the collection. In Apex, you can define your own custom iterators by implementing the Iterator interface.
๐ŸŒ
forceapozee
forceapozee.com โ€บ post โ€บ mastering-iteration-in-apex-using-iterable-for-simplified-loops
Mastering Iteration in Apex: Using Iterable for Simplified Loops
January 30, 2025 - 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. 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.
Top answer
1 of 1
1

There's no notion of Object.getClass() in Apex; the alternative is using instanceof with a known set of types.

Below is modified handler that uses JSON.serialize, then determines whether ofAnyType is an array, object, or some other primitive.

Assuming an array (either a Set or List in Apex), it can be cast to List<Object>. This can be iterated over to determine the instanceof for each member.

An alternative implementation would use ofAnyType instanceof Set<Object_Type_Here>, though is not as abstract.

public static void handler(Object ofAnyType)
{       
    String jsonString = JSON.serialize(ofAnyType);
    System.debug(jsonString);

    // if array, use List<Object>
    if(jsonString.length() > 0 && jsonString.startsWith('[') && jsonString.endsWith(']'))
    {
        List<Object> mapped = (List<Object>)JSON.deserializeUntyped(jsonString);

        // iterate over mapped, check type of each Object o within iteration
        for(Object o : mapped)
        {
            if(o instanceof String)
            {
                System.debug((String)o);
            }
        }
    }

    // if object, use Map<String, Object>
    else if(jsonString.length() > 0 && jsonString.startsWith('{') && jsonString.endsWith('}'))
    {
        Map<String, Object> mapped = (Map<String,Object>)JSON.deserializeUntyped(jsonString);

        // iterate over mapped, check type of each Object o within iteration
        for(Object o : mapped.values())
        {
            if(o instanceof String)
            {
                System.debug((String)o);
            }
        }
    }
}

For quick testing, I saved handler in my StackTesting class. You may use the code below to execute anonymous Apex and see the results.

Integer i = 42;
Set<String> strs = new Set<String>{'hello', 'world'};
Set<Object> objs = new Set<Object>{'hello', 2, new Account(Name = 'Sure')};

StackTesting.handler(i);
StackTesting.handler(strs);
StackTesting.handler(objs);

Note that a more robust implementation would make use of Pattern within Apex, which would take place of the .startsWith and .endsWith for determining whether jsonString is an array or object.

๐ŸŒ
Salesforce
help.salesforce.com โ€บ s โ€บ articleView
Iterate Within For Loops More Easily with Iterable | Salesforce Help
This example implements an Iterable ... MyIterable implements Iterable<String> { public Iterator<String> iterator() { return new Set<String>{'Hello', 'World!'}.iterator(); } } for (String str : new MyIterable()) { System.debug(str); } IdeaExchange: Allow Iterable for Loops in ...
Find elsewhere
๐ŸŒ
Jamessimone
jamessimone.net โ€บ blog โ€บ joys-of-apex โ€บ lazy-iterators
Joys Of Apex: Lazy Iterators - James Simone
The idea for this article has been brewing since then. Their LazyIterator object uses the Decorator pattern to add functionality to the underlying iterators found on all Salesforce List objects 2 โ€” reading through their codebase got me re-excited about working with collections in Apex.
๐ŸŒ
Blogger
salesforcecodes.blogspot.com โ€บ 2020 โ€บ 01 โ€บ how-to-use-custom-iterator-in-apex.html
Salesforce Codes: How to use custom iterator in apex batch class
Use a custom iterator defined using CustomIterable interface ยท You can just use standard apex collections like list as iterator.
๐ŸŒ
Medium
medium.com โ€บ @anuhyadigital โ€บ what-is-interface-iterator-in-apex-bbb987509d0c
What is Interface Iterator in Apex | by Anuhya digital | Medium
September 30, 2024 - An Iterator is a design pattern in Apex that provides a way to access the elements of a collection sequentially without exposing its underlying representation. It allows developers to traverse through data, one element at a time, making it particularly useful when working with large data sets in Salesforce.
๐ŸŒ
Wordpress
suhasrathod.wordpress.com โ€บ 2020 โ€บ 04 โ€บ 10 โ€บ how-to-use-custom-iterator
How to use custom iterator
April 10, 2020 - global class CustomIterable implements Iterator<Account>{ List<Account> accs {get; set;} Integer i {get; set;} public CustomIterable(){ accs = [SELECT Id, Name, NumberOfEmployees FROM Account WHERE Name = 'false']; i = 0; } global boolean hasNext(){ if(i >= accs.size()) { return false; } else { return true; } } global Account next(){ if(i == 8){return null;} i++; return accs[i-1]; } } ... global class example implements iterable<Account>{ global Iterator<Account> Iterator(){ return new CustomIterable(); } }
๐ŸŒ
Grazitti Interactive
grazitti.com โ€บ home โ€บ blog โ€บ implementing batch apex using custom iterables
Implementing Batch Apex Using Custom Iterables
June 15, 2026 - This is an example of a custom iterator with a batch class in Salesforce Apex that cannot be implemented with a query locator:
๐ŸŒ
YouTube
youtube.com โ€บ codeisha
Custom Iterator in Apex | Benefits, Methods & Code Example - YouTube
Learn everything about Custom Iterators in Apex:1. What is a Custom Iterator?2. Why should you use Custom Iterators?3. Where can you implement them?4. Key me...
Published: December 29, 2024
Views: 200
๐ŸŒ
YouTube
youtube.com โ€บ coding with the force
Salesforce Apex Master Class (Ep. 29) - Collection Iteration in Apex (How to Write For Loops) - YouTube
In this episode we go over how to iterate through collections in Apex, why it's useful, when to use it and we do an example of a normal and enhanced for loop...
Published: June 20, 2022
๐ŸŒ
Cloud With Abhi
cloudwithabhi.com โ€บ ๐Ÿ”-simplify-apex-loops-with-the-iterable-interface
๐Ÿ” Simplify Apex Loops with the Iterable Interface
September 30, 2025 - Hereโ€™s the simplest implementation ... MyIterable(List<String> strings) { this.strings = strings; } public Iterator<String> iterator() { return strings.iterator(); } } implements Iterable<String> โ†’ tells Apex this class can be ...
๐ŸŒ
FooBarForce
foobarforce.wordpress.com โ€บ 2012 โ€บ 11 โ€บ 15 โ€บ apex-method-of-the-day-iterator
Apex Method of the Day โ€“ List Iterator | FooBarForce
May 4, 2014 - โ† Apex Method of the Day โ€“ JSON.deserialize(jsonString, List.class) Salesforce as an Identity Provider for Customer Portal โ†’ ยท Posted on November 15, 2012 by Stephen ยท List<T> foo; Iterator<T> bar = foo.iterator(); T baz = bar.next(); ...