How to convert SET to array in APEX?
-
30-09-2019 - |
Question
I have map with key and value and my goal is to get list of 'key'. I am thinking to get it to the array or List. Got to the point where I have key values in the SET but haven't figure out how to convert to the array.
below is my code:
Map<String, String> mmm = new Map<String, String>();
mmm.put('one', 'oneee');
mmm.put('two', 'twooo');
mmm.put('three', 'threeee');
mmm.put('four', 'fourff');
//outputs values in the map
system.debug('=======values()==========>' + mmm.values());
//outputs key in the map
system.debug('=======keyset()===========>' + mmm.keyset());
//get keys in the type SET
SET<string> s = mmm.keyset();
//returns 4
system.debug('------------------------------------' + s.size());
s.arrayTo() //this method does not exist :(
Solution
Use List.addAll
method?
If not - you could always manually loop through the set...
OTHER TIPS
Could you use:
Set keys = mmm.keySet(); List keyList = new List(keys);
You should always used generics for type safety.
Map<String, String> mmm = new Map<String, String>();
mmm.put('one', 'oneee');
mmm.put('two', 'twooo');
mmm.put('three', 'threeee');
mmm.put('four', 'fourff');
List<String> lstKeys = new List<String>(mmm.keyset());
System.debug('Output : '+lstKeys);
As per link : https://salesforce.stackexchange.com/questions/5447/is-there-a-difference-between-an-array-and-a-list-in-apex .
This solution will work.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow