html code

Retrieve the first element from a SET using Apex

Greetings, Trailblazers,

You’re likely aware of the distinction between LIST and SET in Apex. You might be curious about accessing the first (or any) element of a SET without iterating.

Through iteration, this can be easily accomplished.

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

Without the need for iteration – Here’s a straightforward technique,

Set<String> setStr = new Set<String>{'abc', 'xyz'}; //Sample set of String
String first = new List<String> (setStr).get(0); //returns abc

#EnjoyLearning #ContinuousLearning