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
Dinesh Gupta KondapalliDinesh Gupta Kondapalli 

Accessing elements from a Set


As we can access elements from a LIST through an Index, and we can access elements from a MAP through the KEY.. How can we access the elements directly from a SET (apart from iterating it in a loop) ??
NagaNaga (Salesforce Developers) 
Hi Dinesh,

Please follow the below code

User-added image

Please let me know if it helps

Best Regards
Naga Kiran
We can't.

However we can -

1. check whether a Set already contains a value using 'contains()' method.
2. add a value if it does not already contain that using 'add()' method.
3. remove a value if it already has it using 'remove()' method.
4. remove all values that are present in some other list/set using 'removeAll()' method - Complement from Set theory.
5. add all values that are present in some other list/set using 'addAll()' method - Union from Set theory.
6. retain only the values that are present in some other list/set using 'retainAll()' method - Intersection from Set theory.

If this is resolved, please do mark the question as Resolved and the most appropriate/helpful answer as the best answer :).
If none of the answers helped you significantly but its resolved, please post the solution. You may also mark your solution as the best answer.
Dinesh Gupta KondapalliDinesh Gupta Kondapalli
@Naga Kiran,

But with that code, we can only get the first element of the SET right, what if I want to access an element somewhere at middle. I can't.
That's the reason we have a Map along with Set. The purpose of each collection is quite different and a Map is something you need if you want to retrieve elements randomly.

1. Set - You can't access elements. Use to check for existence, non-existence or deduplication.
2. Map - You can access any random element in a Map, if you know the key. Use when you want to access elements in a random order.
3. List - You can access an element if you know its index i.e. the order in which it was added the List.

In Naga's code above, you are retrieving a value from List rather than a Set.