7

Would it be possible to remove bunch of keys from a map in one single statement like this,

Map<String, String> colorCodes = 
   new Map<String, String>();

colorCodes.put('Red', 'FF0000');
colorCodes.put('Blue', '0000A0');

String myColor = colorCodes.remove('Blue','Red'); //this line throwing error
14

In your above example as per doc , Map's remove method takes in only one key as argument and returns a value as return type. you cannot pass a list of strings to the remove method, though I tried something like below based on java's removeall ( undocumented in salesforce map methods )

https://stackoverflow.com/questions/17675804/remove-multiple-keys-from-map-in-efficient-way

http://www.salesforce.com/us/developer/docs/dbcom_apex250/Content/apex_methods_system_map.htm

Map<String, String> colorCodes = 
   new Map<String, String>();

colorCodes.put('Red', 'FF0000');
colorCodes.put('Blue', '0000A0');
colorCodes.put('Blue2', '0000A0');
set<string> remove_keys = new set<string>{'Red','Blue'};
    colorCodes.keySet().removeAll(remove_keys);
system.debug('#### Map after removing keys'+ colorCodes);

13:30:38.052 (52492111)|SYSTEM_METHOD_ENTRY|[9]|System.debug(ANY) 13:30:38.052 (52504469)|USER_DEBUG|[9]|DEBUG|#### Map after removing keys{Blue2=0000A0}

  • I did not know that existed, good find – Phil Hawthorn Jul 29 '14 at 20:35
  • Thanks @rao. I did not see it in the documentation. Somewhat missed from there. Thanks a lot. – Bforce Jul 29 '14 at 20:37
  • I try java syntax in apex and sometimes find hidden bounties like this :P – Rao Jul 29 '14 at 20:37
  • 1
    This is actually documented method on Set: salesforce.com/us/developer/docs/dbcom_apex230/Content/… KeySet - is a set, and it has removeAll method. – Patlatus May 29 '15 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.