Get First Element of SET using Apex

Hello Trailblazers,

As you may already know the difference between LIST and SET in apex and you may be wondering how you can get the first (or any element) of a SET without iteration.

Using Iteration, you can get it easily,

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

Without Iteration – Here is a simple trick,

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

Cheers!

#HappyLearning #KeepLearning

Leave a Comment