Although not documented as a set method, iterator() seems to work just fine on sets:

set<String> strings = new set<String> {'a','b'};
system.debug(LoggingLevel.INFO,'next() on set ='+strings.iterator().next());

DEBUG: next() on set = a

set<Integer> ints = new set<Integer>();
System.debug(LoggingLevel.INFO,'hasNext()? ' + ints.iterator().hasNext());

DEBUG: hasNext()? false

This is handy when for whatever reason, you only care about the first member of a set and avoids converting from sets to lists.

There is, however, a curious example of iterator() on a set being used in an Apex doc example..

String requestLabel = requests.keyset().iterator().next();

Tested in V36 and V38


1 Answer 1


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.

  • hmm. Fascinating that the doc uses iterator() on a keySet() example : developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…. Of course, as you and I both know only too well, there are periodic bugs in the doc.
    – cropredy
    Oct 6, 2016 at 21:25
  • @cropredy I'm pretty sure they weren't meant to put it in the docs. I need to find someone in that team...
    – sfdcfox
    Oct 7, 2016 at 2:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .