开发者

How to convert SET to array in APEX?

开发者 https://www.devze.com 2023-01-28 17:14 出处:网络
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.

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 :(


Use List.addAll method?

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_methods_system_list.htm?SearchType=Stem

If not - you could always manually loop through the set...


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.


A quick and simple way to do this would also be:

new List<String>(mmm.keySet());
//or
new String[mmm.keySet()];

In some code I wrote recently I've got a Set<String> and am passing it into a method that takes a List<String> with methodName( new List<String>(setVariable) ); or methodName(new String[setVariable] );


Yes I know the post is 11+ years old... but it is also what comes up when searching so I put my answer here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号