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 ...
Find elsewhere
🌐
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
🌐
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.
🌐
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.
🌐
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.
Top answer
1 of 1
13

Update

Thanks to Use the Iterable Interface with Set Type, this is no longer an issue. You can use Sets as if they were Iterable.

Original Answer

This is one of those cases where the Type system just falls flat. Set does actually implement the methods for being an Iterable, as mentioned by the methods in the documentation, but does not officially "implement" it (System.assert(stringSet instanceOf Iterable<String>) fails).

The net result is that we have a hybrid object that fails to compile when you try to use it in a context that expects an Iterable, but does work in other cases where you'd expect it to work (and some places you wouldn't, based on other behavior). Salesforce.com has been made aware that types are inherently broken, but there's no idea when or if it'll be fixed.

For now, I'd say that you should not use that method. The reason why is because the cast will ultimately cause Apex Hammer Tests to fail when/if they try to fix this bug, which will mean they'll have to either version it into the compiler, or not be able to fix it at all.

How I would address this for now is to use the slightly more obtuse List constructor:

String mySet_Joined = String.join(new List<String>(mySet), ', ');

This won't fail in future versions but will allow salesforce.com to fix the Iterable/Iterator problem on the Set class. In the meantime, I'll try and get a hold of some people over at salesforce.com to see if I can get more insight on the matter.

When/if I get an answer about this, I'll revise this answer with a recommendation on if you should be casting to Iterable or not.

🌐
Salesforce
help.salesforce.com › s › articleView
Use the Iterable Interface with Set Type | Salesforce Help
The Set class now implements the Iterable interface, so you can directly iterate over sets.