function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mesmailmesmail 

access first element in a set

How can I access the first element in a set?  Example in a list, you can use this to get the first element in the list  

 

Integer x = xList.get(0);

 

What would be a quick equivalent way of doing this in a set?

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
string firstElement = null;
for (string setElement : setElements) {
        firstElement = setElement;
        break;
}

 This would be (marginally) faster, since you break early.

 

You can also:

 

string firstelement =
 (new list<string>(setelements) )[0] );

 Just make sure setElements.isEmpty() is false.

All Answers

varun.sforcevarun.sforce

A set is an unordered collection of primitives or sObjects that do not contain any duplicate elements.

 

So you never know which is first element.

JeffStevensJeffStevens

Can you loop through a SET? Like you can a LIST?

 

string firstElement = null;

for (string setElement : setElements) {

    if (setElement == null) {

        firstElement = setElement;

    }

}

 

 

varun.sforcevarun.sforce

As following....

                

Set<String> setName = new set<String>();
                    
                    setName.add('XYZ');
                    setName.add('ABC');
                    
                    for(String name : setName){
                        System.debug(name);
                    }

sfdcfoxsfdcfox
string firstElement = null;
for (string setElement : setElements) {
        firstElement = setElement;
        break;
}

 This would be (marginally) faster, since you break early.

 

You can also:

 

string firstelement =
 (new list<string>(setelements) )[0] );

 Just make sure setElements.isEmpty() is false.

This was selected as the best answer
mesmailmesmail

Thanks sfdcfox!  That's exactly what I needed.

Seth Wingert 5Seth Wingert 5
If you know the Set is not empty, can also do:
setName.iterator().next();