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