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
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.

🌐
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.
🌐
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.
🌐
Apex Hours
apexhours.com › home › salesforce release notes › preventing collection modification during iteration in apex (set) – winter’25 release
Preventing Collection Modification During Iteration in Apex (Set) - Winter’25 Release - Apex Hours
October 14, 2024 - In Apex, modifying a Set while iterating over it was previously allowed, but it often led to unpredictable behavior. Developers encountered issues such as skipped elements, multiple processes on the same element, or unexpected errors. To address this, from API version 61.0, Apex introduced a restriction that prevents modifying a Set during iteration.
🌐
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 ...
🌐
Salesforce
help.salesforce.com › s › articleView
Iterate Within For Loops More Easily with Iterable | Salesforce Help
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); } IdeaExchange: Allow Iterable for Loops in Apex Code
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.
🌐
Abubakar Solutions
abubakarsolutions.com › mastering-batch-apex-handling-multiple-objects-with-custom-iterators
Mastering Batch Apex: Handling Multiple Objects with Custom Iterators – Abubakar Solutions
April 18, 2025 - The Iterable class returns an instance of our custom Iterator. 🔹 This allows Batch Apex to fetch records from multiple sources.
🌐
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.
🌐
Asagarwal
asagarwal.com › home › #salesforcesummer23 – use the iterable interface with set & list
#SalesforceSummer23 - Use the Iterable Interface with Set & List
July 18, 2023 - July 18, 2023 / Leave a Comment / Apex, SalesforceSummer23 · #1MinuteTip #SalesforceSummer23 The Set class now implements the Iterable interface, so you can directly iterate over sets.
🌐
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
🌐
S2 Labs
s2-labs.com › home › sets in apex
Sets in Apex | Salesforce Developer Tutorials
August 7, 2025 - Apex uses a hash structure for all sets. A set is an unordered collection—you can’t access a set element at a specific index. You can only iterate over set elements.