Access an index for a Set collection?

Is it possible to access the index inside a set?

E.g. here’s a set

Set <integer> numbers = new Set(){1,2,3,4,5,6,7,8};

Is there a way to access the index of the set like so ?

numbers[0]

Answer

You can’t index a Set like you can a List/Array. You can perform typical set operations – such as check if the Set contains an element by value, or remove an element by value. They are typically used for checking membership of data, not retrieving key/value pairs or values by index.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_set.htm

Just curious, what is your requirement where you would like to index a Set? I think a Map or List may be a more appropriate collection to use. If you were using a Set to eliminate duplicates, you could use a List to perform whatever index operations you desired, and then construct a set from the List:

List<Integer> ls = new List<Integer>();
ls.add(1);
ls.add(2);
Set<Integer> s1 = new Set<Integer>(ls);
System.debug(s1); // DEBUG|{1, 2}

Attribution
Source : Link , Question Author : chrisjlee , Answer Author : Brian Mansfield

Leave a Comment